<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('网格交易回测')" />
    <!-- 使用本地ECharts文件 -->
    <script th:src="@{/js/echarts.min.js}"></script>
    <style>
        body {
            background: #f5f5f5;
        }
        
        .container-div {
            padding: 10px;
        }
        
        /* 回测结果卡片区域 */
        .backtest-results {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 12px;
            margin-bottom: 15px;
        }
        
        .result-card {
            background: #fff;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-left: 4px solid #007bff;
        }
        
        .result-card.success {
            border-left-color: #28a745;
        }
        
        .result-card.warning {
            border-left-color: #ffc107;
        }
        
        .result-card.danger {
            border-left-color: #dc3545;
        }
        
        .result-card.info {
            border-left-color: #17a2b8;
        }
        
        .result-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        
        .result-value {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }
        
        .result-value.positive {
            color: #28a745;
        }
        
        .result-value.negative {
            color: #dc3545;
        }
        
        .result-unit {
            font-size: 14px;
            color: #999;
            margin-left: 4px;
        }
        
        /* 图表容器 */
        .chart-container {
            background: #fff;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 12px;
        }
        
        .chart-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 12px;
            padding-bottom: 6px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        #profit-chart {
            width: 100%;
            height: 500px;
            min-width: 800px;
        }
        
        /* 交易明细容器 */
        .transaction-details-container {
            background: #fff;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 12px;
        }
        
        .transaction-details-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
            padding: 10px;
            border-bottom: 1px solid #f0f0f0;
            user-select: none;
        }
        
        .transaction-details-header:hover {
            background: #f8f9fa;
        }
        
        .transaction-details-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        
        .transaction-details-toggle {
            font-size: 14px;
            color: #666;
        }
        
        .transaction-details-content {
            display: none;
            padding-top: 10px;
        }
        
        .transaction-details-content.expanded {
            display: block;
        }
        
        /* 日期分组 */
        .date-group {
            margin-bottom: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .date-group-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 15px;
            background: #f8f9fa;
            cursor: pointer;
            user-select: none;
        }
        
        .date-group-header:hover {
            background: #e9ecef;
        }
        
        .date-group-title {
            font-size: 14px;
            font-weight: 600;
            color: #333;
        }
        
        .date-group-stats {
            font-size: 12px;
            color: #666;
            margin-left: 10px;
        }
        
        .date-group-toggle {
            font-size: 12px;
            color: #666;
        }
        
        .date-group-content {
            display: none;
            background: #fff;
        }
        
        .date-group-content.expanded {
            display: block;
        }
        
        /* 交易明细表格 */
        .transaction-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }
        
        .transaction-table th {
            background: #f8f9fa;
            padding: 10px 12px;
            text-align: center;
            font-size: 13px;
            font-weight: 600;
            color: #333;
            border: 1px solid #e0e0e0;
        }
        
        .transaction-table td {
            padding: 10px 12px;
            text-align: center;
            font-size: 13px;
            color: #333;
            border: 1px solid #e0e0e0;
        }
        
        .transaction-table tr:hover {
            background: #f8f9fa;
        }
        
        .transaction-table tbody tr:nth-child(even) {
            background: #fafafa;
        }
        
        .transaction-table tbody tr:nth-child(even):hover {
            background: #f0f0f0;
        }
        
        .transaction-table .date-cell {
            font-weight: 500;
        }
        
        .transaction-table .value-cell {
            white-space: nowrap;
        }
        
        .transaction-table .profit-positive {
            color: #dc3545;
            font-weight: 600;
        }
        
        .transaction-table .profit-negative {
            color: #28a745;
            font-weight: 600;
        }
        
        .transaction-table .sort-icon {
            color: #999;
            cursor: pointer;
            margin-left: 5px;
            font-size: 12px;
        }
        
        .transaction-table .sort-icon:hover {
            color: #007bff;
        }
        
        .transaction-table .expand-icon {
            color: #666;
            cursor: pointer;
            font-size: 14px;
            padding: 2px 5px;
        }
        
        .transaction-table .expand-icon:hover {
            color: #007bff;
        }
        
        .transaction-table .detail-link {
            color: #007bff;
            cursor: pointer;
            text-decoration: underline;
        }
        
        .transaction-table .detail-link:hover {
            color: #0056b3;
        }
        
        .trade-type-buy {
            color: #dc3545;
            font-weight: 600;
        }
        
        .trade-type-sell {
            color: #28a745;
            font-weight: 600;
        }
        
        /* 详细交易记录表格 */
        .detail-transaction-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
            margin-top: 10px;
        }
        
        .detail-transaction-table th {
            background: #f0f0f0;
            padding: 6px 10px;
            text-align: left;
            font-size: 12px;
            font-weight: 600;
            color: #666;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .detail-transaction-table td {
            padding: 6px 10px;
            font-size: 12px;
            color: #333;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .detail-transaction-table tr:hover {
            background: #f8f9fa;
        }
        
        /* 买卖图标 */
        .trade-icon {
            display: inline-block;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            margin-right: 6px;
            vertical-align: middle;
        }
        
        .trade-icon-buy {
            background: #dc3545;
            color: #fff;
        }
        
        .trade-icon-sell {
            background: #28a745;
            color: #fff;
        }
        
        .detail-transaction-table .time-cell {
            display: flex;
            align-items: center;
        }
        
        /* 搜索区域 */
        .search-area {
            background: #fff;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 10px;
        }
        
        .search-form {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: flex-end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .form-group label {
            font-size: 14px;
            color: #666;
        }
        
        .form-group input,
        .form-group select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #007bff;
        }
        
        .btn-primary {
            background: #007bff;
            color: #fff;
            border: none;
            padding: 8px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .btn-primary:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        
        /* 下拉框样式 */
        .dropdown-item {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        
        .dropdown-item:hover {
            background-color: #f5f5f5;
        }
        
        .dropdown-item.selected {
            background-color: #007bff !important;
            color: white !important;
        }
        
        #securityDropdown {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            background: white;
            border: 1px solid #ccc;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            width: 100%;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-radius: 4px;
            margin-top: 2px;
        }
        
        .security-input-wrapper {
            position: relative;
            width: 160px;
        }
        
        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .error-message {
            text-align: center;
            padding: 20px;
            color: #dc3545;
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
            margin: 20px 0;
        }
        
        .no-data {
            text-align: center;
            padding: 50px;
            color: #999;
            font-size: 16px;
        }
        
        /* 回测周期组样式 */
        .period-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .period-group label {
            font-size: 14px;
            color: #666;
        }
        
        .period-inputs {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .period-input-wrapper {
            position: relative;
            flex: 1;
        }
        
        .period-separator {
            color: #999;
            font-size: 14px;
            padding: 0 5px;
        }
        
        /* 触发条件组样式 */
        .trigger-conditions {
            background: #fff;
            border-radius: 8px;
            padding: 0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 10px;
        }
        
        .trigger-conditions-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            padding: 8px 20px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .trigger-conditions-content {
            padding: 0;
        }
        
        .trigger-condition-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 20px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .trigger-condition-row:last-child {
            border-bottom: none;
        }
        
        .trigger-condition-label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #666;
            position: relative;
        }
        
        .trigger-condition-label .info-icon {
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: #e0e0e0;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            cursor: help;
            font-style: normal;
            position: relative;
        }
        
        .trigger-condition-info-tooltip {
            position: absolute;
            top: calc(100% + 8px);
            left: 0;
            background: #333;
            color: white;
            padding: 12px;
            border-radius: 6px;
            font-size: 12px;
            line-height: 1.6;
            white-space: normal;
            z-index: 1001;
            display: none;
            min-width: 280px;
            max-width: 400px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            pointer-events: none;
        }
        
        .trigger-condition-info-tooltip.show {
            display: block;
        }
        
        .trigger-condition-info-tooltip::after {
            content: '';
            position: absolute;
            bottom: 100%;
            left: 20px;
            border: 6px solid transparent;
            border-bottom-color: #333;
        }
        
        .trigger-condition-info-tooltip-content {
            margin: 0;
        }
        
        .trigger-condition-info-tooltip-content p {
            margin: 0 0 8px 0;
        }
        
        .trigger-condition-info-tooltip-content p:last-child {
            margin-bottom: 0;
        }
        
        .trigger-condition-control {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .trigger-condition-control-vertical {
            flex-direction: column;
            align-items: flex-end;
            gap: 8px;
        }
        
        .trigger-condition-input-wrapper-horizontal {
            display: flex;
            align-items: center;
            gap: 8px;
            justify-content: flex-end;
        }
        
        .trigger-condition-select {
            padding: 6px 30px 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background: white;
            cursor: pointer;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23999' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 10px center;
            background-size: 12px;
        }
        
        .trigger-condition-value {
            font-size: 14px;
            font-weight: bold;
            color: #333;
            padding: 6px 12px;
        }
        
        .trigger-condition-input-wrapper {
            position: relative;
            display: flex;
            align-items: center;
        }
        
        .trigger-condition-input-value {
            padding: 6px 30px 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            font-weight: bold;
            color: #333;
            width: 120px;
            background: white;
        }
        
        .trigger-condition-input-value:focus {
            outline: none;
            border-color: #007bff;
        }
        
        .trigger-condition-input-value::placeholder {
            font-size: 11px;
        }
        
        .trigger-condition-dropdown-icon {
            position: absolute;
            right: 8px;
            width: 16px;
            height: 16px;
            cursor: pointer;
            color: #999;
            display: flex;
            align-items: center;
            justify-content: center;
            pointer-events: auto;
        }
        
        .trigger-condition-dropdown-menu {
            display: none;
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            z-index: 1000;
            min-width: 150px;
            margin-top: 2px;
        }
        
        .trigger-condition-dropdown-menu.show {
            display: block;
        }
        
        .trigger-condition-dropdown-item {
            padding: 10px 15px;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .trigger-condition-dropdown-item:last-child {
            border-bottom: none;
        }
        
        .trigger-condition-dropdown-item:hover {
            background: #f8f9fa;
        }
        
        .trigger-condition-input-group {
            display: flex;
            align-items: center;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #fff;
            overflow: hidden;
            gap: 0;
        }
        
        /* 每上涨/每下跌输入组的容器加宽，确保文字和按钮不重叠 */
        .rise-fall-value-input-group {
            min-width: 140px;
            padding: 0 4px;
            justify-content: space-between;
        }
        
        .trigger-condition-input-btn {
            width: 32px;
            height: 32px;
            border: none;
            background: transparent;
            color: #666;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            padding: 0;
        }
        
        .trigger-condition-input-btn:hover {
            background: #e9ecef;
        }
        
        .trigger-condition-input {
            border: none;
            background: transparent;
            padding: 6px 0;
            font-size: 14px;
            width: 100px;
            min-width: 60px;
            text-align: center;
            color: #999;
            flex: 0 0 auto;
            margin: 0;
            box-sizing: border-box;
            outline: none;
            letter-spacing: 0;
        }
        
        /* 每上涨/每下跌输入框固定宽度 */
        #riseValue,
        #fallValue {
            width: 5ch !important;
            min-width: 5ch !important;
            max-width: 5ch !important;
            flex: 0 0 5ch !important;
            flex-shrink: 0 !important;
            flex-grow: 0 !important;
        }
        
        /* 每上涨/每下跌输入框的placeholder文字样式 */
        #riseValue::placeholder,
        #fallValue::placeholder {
            font-size: 11px !important;
        }
        
        /* 每上涨/每下跌输入框输入内容的字体大小保持14px */
        #riseValue:not(:placeholder-shown),
        #fallValue:not(:placeholder-shown) {
            font-size: 14px !important;
        }
        
        /* 确保包含每上涨/每下跌输入框的容器也保持固定宽度 */
        .rise-fall-value-wrapper {
            width: 5ch !important;
            min-width: 5ch !important;
            max-width: 5ch !important;
            flex-shrink: 0 !important;
            flex-grow: 0 !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }
        
        .trigger-condition-input:focus {
            outline: none;
            color: #333;
        }
        
        .trigger-condition-input::placeholder {
            font-size: 11px;
        }
        
        .trigger-condition-input-wrapper-relative {
            position: relative;
        }
        
        .trigger-condition-tooltip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            margin-bottom: 5px;
            background: #ff9800;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 500;
            white-space: nowrap;
            z-index: 1000;
            display: none;
        }
        
        .trigger-condition-tooltip::after {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            border: 5px solid transparent;
            border-top-color: #ff9800;
        }
        
        .trigger-condition-tooltip.show {
            display: block;
        }
        
        .trigger-condition-hands-tooltip {
            position: absolute;
            top: 0;
            left: 0;
            transform: translate(-100%, -100%);
            margin-right: 4px;
            margin-bottom: 4px;
            background: #007bff;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 500;
            white-space: nowrap;
            z-index: 1000;
            display: none;
        }
        
        .trigger-condition-hands-tooltip::after {
            content: '';
            position: absolute;
            bottom: -4px;
            right: 4px;
            border: 4px solid transparent;
            border-top-color: #007bff;
        }
        
        .trigger-condition-hands-tooltip.show {
            display: block;
        }
        
        .trigger-condition-input-value-display {
            color: #999;
            font-weight: 500;
        }
        
        .trigger-condition-input-value-display:not(:placeholder-shown) {
            color: #dc3545;
        }
        
        .trigger-condition-input-wrapper-with-symbols {
            position: relative;
            display: inline-flex;
            align-items: center;
            gap: 0;
            margin: 0;
            padding: 0;
            white-space: nowrap;
            flex-shrink: 0;
        }
        
        .trigger-condition-input-symbol-before {
            color: #dc3545;
            font-weight: 500;
            margin: 0;
            padding: 0;
            display: none;
            line-height: 1;
            vertical-align: middle;
            flex-shrink: 0;
        }
        
        .trigger-condition-input-symbol-before.show {
            display: inline-block;
        }
        
        .trigger-condition-input-symbol-after {
            color: #dc3545;
            font-weight: 500;
            margin: 0;
            padding: 0;
            display: none;
            line-height: 1;
            vertical-align: middle;
            flex-shrink: 0;
        }
        
        .trigger-condition-input-symbol-after.show {
            display: inline-block;
        }
        
        .trigger-condition-input-symbol-before.fall {
            color: #28a745;
        }
        
        .trigger-condition-input-symbol-after.fall {
            color: #28a745;
        }
        
        .trigger-condition-input-fall {
            color: #999;
            font-weight: 500;
        }
        
        .trigger-condition-input-fall:not(:placeholder-shown) {
            color: #28a745;
        }
        
        .trigger-condition-action-text {
            font-size: 14px;
            font-weight: 500;
            padding: 0 8px;
        }
        
        .trigger-condition-action-text.sell {
            color: #007bff;
        }
        
        .trigger-condition-action-text.buy {
            color: #dc3545;
        }
        
        .trigger-condition-unit-text {
            font-size: 14px;
            color: #666;
            margin-left: 8px;
            font-weight: normal;
        }
        
        .trigger-condition-multiplier-buttons {
            display: flex;
            flex-direction: row;
            gap: 4px;
            width: auto;
            flex-wrap: wrap;
        }
        
        .trigger-condition-multiplier-btn {
            padding: 4px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #fff;
            color: #666;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s;
            text-align: center;
            flex: 0 0 auto;
        }
        
        .trigger-condition-multiplier-btn:hover {
            background: #f5f5f5;
            border-color: #007bff;
            color: #007bff;
        }
        
        .trigger-condition-multiplier-btn:active {
            background: #e9ecef;
        }
        
        .trigger-condition-multiplier-btn:disabled {
            background: #f5f5f5;
            color: #999;
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        .trigger-condition-multiplier-btn.active {
            background: #007bff;
            border-color: #007bff;
            color: #fff;
            font-weight: bold;
        }
        
        .trigger-condition-multiplier-btn.active:hover {
            background: #0056b3;
            border-color: #0056b3;
        }
        
        
        /* 自定义倍数模态框样式 */
        .custom-multiplier-modal {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 10000;
            display: none;
        }
        
        .custom-multiplier-modal-overlay {
            display: none;
        }
        
        .custom-multiplier-modal-content {
            position: absolute;
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
            width: 200px;
            z-index: 10001;
            animation: modalFadeIn 0.2s ease-out;
            border: 1px solid #ddd;
            bottom: 100%;
            right: 0;
            margin-bottom: 5px;
        }
        
        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-5px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .custom-multiplier-modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 12px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .custom-multiplier-modal-header h3 {
            margin: 0;
            font-size: 14px;
            font-weight: 600;
            color: #333;
        }
        
        .custom-multiplier-modal-close {
            background: none;
            border: none;
            font-size: 18px;
            color: #999;
            cursor: pointer;
            padding: 0;
            width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: color 0.2s;
            line-height: 1;
        }
        
        .custom-multiplier-modal-close:hover {
            color: #333;
        }
        
        .custom-multiplier-modal-body {
            padding: 12px;
        }
        
        .custom-multiplier-form-group {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        
        .custom-multiplier-input {
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 13px;
            color: #333;
            transition: border-color 0.2s;
            width: 100%;
            box-sizing: border-box;
        }
        
        .custom-multiplier-input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
        }
        
        .custom-multiplier-error {
            color: #dc3545;
            font-size: 11px;
            margin-top: -4px;
        }
        
        .custom-multiplier-modal-footer {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 8px;
            padding: 10px 12px;
            border-top: 1px solid #f0f0f0;
        }
        
        .custom-multiplier-btn {
            padding: 5px 12px;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
        }
        
        .custom-multiplier-btn-cancel {
            background: #f5f5f5;
            color: #666;
        }
        
        .custom-multiplier-btn-cancel:hover {
            background: #e9ecef;
            color: #333;
        }
        
        .custom-multiplier-btn-confirm {
            background: #007bff;
            color: #fff;
        }
        
        .custom-multiplier-btn-confirm:hover {
            background: #0056b3;
        }
        
        .custom-multiplier-btn-confirm:active {
            transform: scale(0.98);
        }
        
        /* 自定义倍数按钮容器，用于定位模态框 */
        .custom-multiplier-btn-wrapper {
            position: relative;
        }
        
        /* 禁用状态样式 */
        .form-control-disabled,
        .form-control-disabled:focus {
            background-color: #f5f5f5 !important;
            cursor: not-allowed !important;
            opacity: 0.6;
        }
        
        .trigger-condition-input-group.disabled {
            opacity: 0.6;
        }
        
        .trigger-condition-input-group.disabled .trigger-condition-input-btn {
            pointer-events: none;
            cursor: not-allowed;
        }
        
        .trigger-condition-input-group.disabled .trigger-condition-input {
            cursor: not-allowed;
        }
        
        .trigger-condition-select.disabled {
            background-color: #f5f5f5 !important;
            cursor: not-allowed !important;
            opacity: 0.6;
        }
        
        /* 开关样式 */
        .trigger-condition-toggle {
            position: relative;
            display: inline-block;
            width: 44px;
            height: 24px;
        }
        
        .trigger-condition-toggle input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .trigger-condition-toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }
        
        .trigger-condition-toggle-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        .trigger-condition-toggle input:checked + .trigger-condition-toggle-slider {
            background-color: #007bff;
        }
        
        .trigger-condition-toggle input:checked + .trigger-condition-toggle-slider:before {
            transform: translateX(20px);
        }
        
        .trigger-condition-toggle input:disabled + .trigger-condition-toggle-slider {
            opacity: 0.6;
            cursor: not-allowed;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <!-- 搜索区域 -->
    <div class="search-area">
        <form id="backtest-form" class="search-form" style="justify-content: center; align-items: center; gap: 15px;">
            <div class="form-group security-input-wrapper" style="margin: 0;">
                <input type="text" id="securitySelect" placeholder="请输入名称或代码" autocomplete="off"/>
                <input type="hidden" id="securitySymbol" name="symbol"/>
                <div id="securityDropdown"></div>
            </div>
        </form>
    </div>
    
    <!-- 回测周期区域 -->
    <div class="trigger-conditions">
        <div class="trigger-conditions-title">回测周期</div>
        <div class="trigger-conditions-content">
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>日期范围</span>
                </div>
                <div class="trigger-condition-control trigger-condition-control-vertical">
                    <div class="period-inputs" style="display: flex; align-items: center; gap: 10px;">
                        <div class="period-input-wrapper" style="position: relative; width: 100px;">
                            <input type="text" id="startDate" name="startDate" class="trigger-condition-input-value" placeholder="开始日期" readonly style="cursor: pointer; width: 100%; padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;"/>
                            <div id="startDateCalendar" style="display: none; position: absolute; top: 100%; right: 0; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); z-index: 1000; width: 280px; padding: 10px; margin-top: 2px;"></div>
                        </div>
                        <span style="color: #666; font-size: 14px;">~</span>
                        <div class="period-input-wrapper" style="position: relative; width: 100px;">
                            <input type="text" id="endDate" name="endDate" class="trigger-condition-input-value" placeholder="结束日期" readonly style="cursor: pointer; width: 100%; padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;"/>
                            <div id="endDateCalendar" style="display: none; position: absolute; top: 100%; right: 0; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); z-index: 1000; width: 280px; padding: 10px; margin-top: 2px;"></div>
                        </div>
                    </div>
                    <div class="trigger-condition-multiplier-buttons date-range-buttons" style="margin-top: 8px;">
                        <button type="button" class="trigger-condition-multiplier-btn date-range-btn" onclick="setDateRange(1)">近1月</button>
                        <button type="button" class="trigger-condition-multiplier-btn date-range-btn" onclick="setDateRange(3)">近3月</button>
                        <button type="button" class="trigger-condition-multiplier-btn date-range-btn" onclick="setDateRange(6)">近半年</button>
                        <button type="button" class="trigger-condition-multiplier-btn date-range-btn" onclick="setDateRange(12)">近1年</button>
                        <button type="button" class="trigger-condition-multiplier-btn date-range-btn" onclick="setDateRange(24)">近2年</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 触发条件区域 -->
    <div class="trigger-conditions">
        <div class="trigger-conditions-title">触发条件</div>
        <div class="trigger-conditions-content">
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>涨跌类型</span>
                </div>
                <div class="trigger-condition-control">
                    <select id="riseFallType" class="trigger-condition-select">
                        <option value="1">按百分比</option>
                        <option value="2">按差价</option>
                    </select>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>初始基准价</span>
                    <span class="info-icon" id="basePriceInfoIcon">
                        ?
                        <div id="basePriceInfoTooltip" class="trigger-condition-info-tooltip">
                            <div class="trigger-condition-info-tooltip-content">
                                <p>初始基准价是网格交易第一次运行时的参考价格，系统按照此价格计算第一次触发买入或卖出的价格。</p>
                                <p>基准价格是动态变化的，网格交易条件单每触发一次后，将以此触发价为最新基准价。</p>
                            </div>
                        </div>
                    </span>
                </div>
                <div class="trigger-condition-control">
                    <div class="trigger-condition-input-wrapper">
                        <input type="text" id="initialBasePrice" class="trigger-condition-input-value" placeholder="输入基准价" value=""/>
                        <span class="trigger-condition-dropdown-icon">▼</span>
                        <div id="basePriceDropdown" class="trigger-condition-dropdown-menu">
                            <div class="trigger-condition-dropdown-item" onclick="fillPreviousClosePrice()">开始日昨收价</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>每上涨</span>
                </div>
                <div class="trigger-condition-control">
                    <div class="trigger-condition-input-wrapper-relative">
                        <div class="trigger-condition-input-group rise-fall-value-input-group">
                            <button type="button" class="trigger-condition-input-btn" onclick="decreaseRiseValue()">−</button>
                            <div class="trigger-condition-input-wrapper-with-symbols rise-fall-value-wrapper">
                                <span id="riseValueSymbolBefore" class="trigger-condition-input-symbol-before">+</span>
                                <input type="text" id="riseValue" class="trigger-condition-input trigger-condition-input-value-display" placeholder="涨幅(%)" value="" style="padding-left: 0; padding-right: 0;"/>
                                <span id="riseValueSymbolAfter" class="trigger-condition-input-symbol-after">%</span>
                            </div>
                            <button type="button" class="trigger-condition-input-btn" onclick="increaseRiseValue()">+</button>
                        </div>
                        <div id="riseValueTooltip" class="trigger-condition-tooltip"></div>
                    </div>
                    <span class="trigger-condition-action-text sell">卖出</span>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>每下跌</span>
                </div>
                <div class="trigger-condition-control">
                    <div class="trigger-condition-input-wrapper-relative">
                        <div class="trigger-condition-input-group rise-fall-value-input-group">
                            <button type="button" class="trigger-condition-input-btn" onclick="decreaseFallValue()">−</button>
                            <div class="trigger-condition-input-wrapper-with-symbols rise-fall-value-wrapper">
                                <span id="fallValueSymbolBefore" class="trigger-condition-input-symbol-before fall">-</span>
                                <input type="text" id="fallValue" class="trigger-condition-input trigger-condition-input-fall" placeholder="跌幅(%)" value="" style="padding-left: 0; padding-right: 0;"/>
                                <span id="fallValueSymbolAfter" class="trigger-condition-input-symbol-after fall">%</span>
                            </div>
                            <button type="button" class="trigger-condition-input-btn" onclick="increaseFallValue()">+</button>
                        </div>
                        <div id="fallValueTooltip" class="trigger-condition-tooltip"></div>
                    </div>
                    <span class="trigger-condition-action-text buy">买入</span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 委托设置区域 -->
    <div class="trigger-conditions">
        <div class="trigger-conditions-title">委托设置</div>
        <div class="trigger-conditions-content">
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>单笔数量</span>
                </div>
                <div class="trigger-condition-control">
                    <div class="trigger-condition-input-wrapper-relative">
                        <div class="trigger-condition-input-group">
                            <button type="button" class="trigger-condition-input-btn" onclick="decreaseSingleTradeQuantity()">−</button>
                            <input type="text" id="singleTradeQuantity" class="trigger-condition-input" placeholder="输入数量" value=""/>
                            <button type="button" class="trigger-condition-input-btn" onclick="increaseSingleTradeQuantity()">+</button>
                        </div>
                        <div id="singleTradeQuantityTooltip" class="trigger-condition-hands-tooltip"></div>
                    </div>
                    <span id="singleTradeQuantityUnit" class="trigger-condition-unit-text" style="display: none;"></span>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>初始持仓</span>
                    <span class="info-icon" id="initialPositionInfoIcon">
                        ?
                        <div id="initialPositionInfoTooltip" class="trigger-condition-info-tooltip">
                            <div class="trigger-condition-info-tooltip-content">
                                <p>初始持仓是网格回测开始日持有的底仓数量。建仓价格默认为回测开始日的昨收价。</p>
                            </div>
                        </div>
                    </span>
                </div>
                <div class="trigger-condition-control trigger-condition-control-vertical">
                    <div class="trigger-condition-input-wrapper-horizontal">
                        <div class="trigger-condition-input-wrapper-relative">
                            <div class="trigger-condition-input-group">
                                <button type="button" class="trigger-condition-input-btn" onclick="decreaseInitialPosition()">−</button>
                                <input type="text" id="initialPosition" class="trigger-condition-input" placeholder="输入持仓" value=""/>
                                <button type="button" class="trigger-condition-input-btn" onclick="increaseInitialPosition()">+</button>
                            </div>
                            <div id="initialMarketValueTooltip" class="trigger-condition-tooltip"></div>
                            <div id="initialPositionTooltip" class="trigger-condition-hands-tooltip"></div>
                        </div>
                        <span id="initialPositionUnit" class="trigger-condition-unit-text" style="display: none;"></span>
                    </div>
                    <div class="trigger-condition-multiplier-buttons">
                        <span style="margin-right: 8px; color: #666; font-size: 12px;">单笔数量倍数</span>
                        <button type="button" class="trigger-condition-multiplier-btn" onclick="setInitialPositionMultiplier(5)">5倍</button>
                        <button type="button" class="trigger-condition-multiplier-btn" onclick="setInitialPositionMultiplier(10)">10倍</button>
                        <button type="button" class="trigger-condition-multiplier-btn" onclick="setInitialPositionMultiplier(15)">15倍</button>
                        <button type="button" class="trigger-condition-multiplier-btn" onclick="setInitialPositionMultiplier(20)">20倍</button>
                        <div class="custom-multiplier-btn-wrapper">
                            <button type="button" class="trigger-condition-multiplier-btn" onclick="showCustomMultiplierInput()">自定义倍数</button>
                            <!-- 自定义倍数模态框 -->
                            <div id="customMultiplierModal" class="custom-multiplier-modal" style="display: none;">
                                <div class="custom-multiplier-modal-overlay"></div>
                                <div class="custom-multiplier-modal-content">
                                    <div class="custom-multiplier-modal-header">
                                        <h3>自定义倍数</h3>
                                        <button type="button" class="custom-multiplier-modal-close" onclick="hideCustomMultiplierModal()">&times;</button>
                                    </div>
                                    <div class="custom-multiplier-modal-body">
                                        <div class="custom-multiplier-form-group">
                                            <input type="text" id="customMultiplierInput" class="custom-multiplier-input" placeholder="请输入自定义倍数" value=""/>
                                            <div id="customMultiplierError" class="custom-multiplier-error" style="display: none;"></div>
                                        </div>
                                    </div>
                                    <div class="custom-multiplier-modal-footer">
                                        <button type="button" class="custom-multiplier-btn custom-multiplier-btn-cancel" onclick="hideCustomMultiplierModal()">取消</button>
                                        <button type="button" class="custom-multiplier-btn custom-multiplier-btn-confirm" onclick="confirmCustomMultiplier()">确定</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>初始可用资金</span>
                    <span class="info-icon" id="initialAvailableFundsInfoIcon">
                        ?
                        <div id="initialAvailableFundsInfoTooltip" class="trigger-condition-info-tooltip">
                            <div class="trigger-condition-info-tooltip-content">
                                <p>初始可用资金是回测开始日持有的可以资金。如果不填写则表示无限资金。</p>
                            </div>
                        </div>
                    </span>
                </div>
                <div class="trigger-condition-control trigger-condition-control-vertical">
                    <div style="display: flex; align-items: center;">
                        <input type="text" id="initialAvailableFunds" class="trigger-condition-input-value" placeholder="输入资金(选填)" value="" style="width: 120px;"/>
                        <span class="trigger-condition-unit-text" style="margin-left: 8px;">元</span>
                    </div>
                    <div class="trigger-condition-multiplier-buttons available-funds-buttons" style="margin-top: 8px;">
                        <span style="margin-right: 8px; color: #666; font-size: 12px;">初始市值倍数</span>
                        <button type="button" class="trigger-condition-multiplier-btn available-funds-btn" onclick="setAvailableFundsMultiplier(0.25)">0.25倍</button>
                        <button type="button" class="trigger-condition-multiplier-btn available-funds-btn" onclick="setAvailableFundsMultiplier(0.5)">0.5倍</button>
                        <button type="button" class="trigger-condition-multiplier-btn available-funds-btn" onclick="setAvailableFundsMultiplier(1)">1倍</button>
                        <button type="button" class="trigger-condition-multiplier-btn available-funds-btn" onclick="setAvailableFundsMultiplier(1.5)">1.5倍</button>
                        <div class="custom-multiplier-btn-wrapper">
                            <button type="button" class="trigger-condition-multiplier-btn available-funds-btn" onclick="showCustomAvailableFundsMultiplierInput()">自定义倍数</button>
                            <!-- 自定义倍数模态框 -->
                            <div id="customAvailableFundsMultiplierModal" class="custom-multiplier-modal" style="display: none;">
                                <div class="custom-multiplier-modal-overlay"></div>
                                <div class="custom-multiplier-modal-content">
                                    <div class="custom-multiplier-modal-header">
                                        <h3>自定义倍数</h3>
                                        <button type="button" class="custom-multiplier-modal-close" onclick="hideCustomAvailableFundsMultiplierModal()">&times;</button>
                                    </div>
                                    <div class="custom-multiplier-modal-body">
                                        <div class="custom-multiplier-form-group">
                                            <input type="text" id="customAvailableFundsMultiplierInput" class="custom-multiplier-input" placeholder="请输入自定义倍数" value=""/>
                                            <div id="customAvailableFundsMultiplierError" class="custom-multiplier-error" style="display: none;"></div>
                                        </div>
                                    </div>
                                    <div class="custom-multiplier-modal-footer">
                                        <button type="button" class="custom-multiplier-btn custom-multiplier-btn-cancel" onclick="hideCustomAvailableFundsMultiplierModal()">取消</button>
                                        <button type="button" class="custom-multiplier-btn custom-multiplier-btn-confirm" onclick="confirmCustomAvailableFundsMultiplier()">确定</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 高级设置区域 -->
    <div class="trigger-conditions">
        <div class="trigger-conditions-title">高级设置</div>
        <div class="trigger-conditions-content">
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>价格区间</span>
                </div>
                <div class="trigger-condition-control">
                    <input type="text" id="priceRangeMin" class="trigger-condition-input-value" placeholder="最低价(选填)" value="" style="width: 100px; padding-right: 12px;"/>
                    <span style="margin: 0 8px; color: #666;">~</span>
                    <input type="text" id="priceRangeMax" class="trigger-condition-input-value" placeholder="最高价(选填)" value="" style="width: 100px; padding-right: 12px;"/>
                    <span class="trigger-condition-unit-text" style="margin-left: 8px;">元</span>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>持仓范围</span>
                </div>
                <div class="trigger-condition-control">
                    <div class="trigger-condition-input-wrapper-relative" style="display: inline-block; margin: 0; padding: 0; vertical-align: top;">
                        <input type="text" id="positionRangeMin" class="trigger-condition-input-value" placeholder="最小持仓(选填)" value="" style="width: 100px; padding-right: 12px;"/>
                        <div id="positionRangeMinTooltip" class="trigger-condition-hands-tooltip"></div>
                    </div>
                    <span style="margin: 0 8px; color: #666;">~</span>
                    <div class="trigger-condition-input-wrapper-relative" style="display: inline-block; margin: 0; padding: 0; vertical-align: top;">
                        <input type="text" id="positionRangeMax" class="trigger-condition-input-value" placeholder="最大持仓(选填)" value="" style="width: 100px; padding-right: 12px;"/>
                        <div id="positionRangeMaxTooltip" class="trigger-condition-hands-tooltip"></div>
                    </div>
                    <span id="positionRangeMaxUnit" class="trigger-condition-unit-text" style="display: none; margin-left: 8px;"></span>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>倍数委托</span>
                </div>
                <div class="trigger-condition-control">
                    <label class="trigger-condition-toggle">
                        <input type="checkbox" id="multiplierOrder" />
                        <span class="trigger-condition-toggle-slider"></span>
                    </label>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 手续费设置区域 -->
    <div class="trigger-conditions">
        <div class="trigger-conditions-title">手续费设置</div>
        <div class="trigger-conditions-content">
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>佣金万几</span>
                </div>
                <div class="trigger-condition-control">
                    <span class="trigger-condition-unit-text" style="margin-right: 8px;">万</span>
                    <input type="text" id="commissionTenThousandth" class="trigger-condition-input-value" placeholder="佣金万几" value="2.5" style="width: 100px; padding-right: 12px;"/>
                </div>
            </div>
            <div class="trigger-condition-row">
                <div class="trigger-condition-label">
                    <span>是否免五</span>
                </div>
                <div class="trigger-condition-control">
                    <label class="trigger-condition-toggle">
                        <input type="checkbox" id="freeMinimumCommission" />
                        <span class="trigger-condition-toggle-slider"></span>
                    </label>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 开始回测按钮 -->
    <div style="text-align: center; margin: 10px 0; padding-bottom: 10px;">
        <button type="button" class="btn-primary" onclick="startBacktest()">开始回测</button>
    </div>
    
    <!-- 回测结果区域 -->
    <div id="results-area" style="display: none; margin-top: 10px;">
        <!-- 回测结果卡片 -->
        <div class="backtest-results">
            <div class="result-card success">
                <div class="result-label">网格收益率</div>
                <div class="result-value" id="gridProfitRate">--</div>
            </div>
            <div class="result-card info">
                <div class="result-label">个股同期涨幅</div>
                <div class="result-value" id="stockRiseRate">--</div>
            </div>
            <div class="result-card warning">
                <div class="result-label">超额收益率</div>
                <div class="result-value" id="excessProfitRate">--</div>
            </div>
            <div class="result-card">
                <div class="result-label">期初总资产</div>
                <div class="result-value" id="initialTotalAssets">--<span class="result-unit">元</span></div>
            </div>
            <div class="result-card">
                <div class="result-label">期末总资产</div>
                <div class="result-value" id="finalTotalAssets">--<span class="result-unit">元</span></div>
            </div>
            <div class="result-card">
                <div class="result-label">交易成本</div>
                <div class="result-value" id="tradeCost">--<span class="result-unit">元</span></div>
            </div>
            <div class="result-card info">
                <div class="result-label">买入次数</div>
                <div class="result-value" id="buyCount">--<span class="result-unit">次</span></div>
            </div>
            <div class="result-card info">
                <div class="result-label">卖出次数</div>
                <div class="result-value" id="sellCount">--<span class="result-unit">次</span></div>
            </div>
            <div class="result-card danger">
                <div class="result-label">最大回撤</div>
                <div class="result-value" id="maxDrawdown">--</div>
            </div>
        </div>
        
        <!-- 回测收益率走势图 -->
        <div class="chart-container">
            <div class="chart-title">回测收益率走势</div>
            <div id="profit-chart"></div>
        </div>
        
        <!-- 交易明细 -->
        <div class="transaction-details-container">
            <div class="transaction-details-header" onclick="toggleTransactionDetails()">
                <div class="transaction-details-title">交易明细</div>
                <div class="transaction-details-toggle" id="transactionDetailsToggle">展开 ▼</div>
            </div>
            <div class="transaction-details-content" id="transactionDetailsContent">
                <div id="transactionDetailsList"></div>
            </div>
        </div>
    </div>
    
    <!-- 加载状态 -->
    <div id="loading-area" class="loading" style="display: none;">
        <i class="fa fa-spinner fa-spin"></i> 正在回测中，请稍候...
    </div>
    
    <!-- 错误信息 -->
    <div id="error-area" class="error-message" style="display: none;"></div>
    
    <!-- 无数据提示 -->
    <div id="no-data-area" class="no-data" style="display: none;">
        暂无回测数据，请先进行回测
    </div>
</div>

<th:block th:include="include :: footer" />
<!-- 证券选择组件 - 必须在 jQuery 加载后 -->
<script th:src="@{/js/security-selector.js}"></script>
<!-- 证券日期选择组件 - 必须在 jQuery 加载后 -->
<script th:src="@{/js/security-date-picker.js}"></script>
<script th:inline="javascript">
    var prefix = ctx + "security/grid-trading-backtest";
    var apiPrefix = ctx + "security/";
    var profitChart = null;
    var startDatePicker = null;
    var endDatePicker = null;
    var securitySelector = null; // 证券选择组件实例
    var currentMinTradeQuantity = null; // 当前选中证券的最小交易数量
    var currentTradeUnit = null; // 当前选中证券的交易单位
    
    $(function() {
        // 初始化图表
        initChart();
        
        // 初始化证券选择组件
        securitySelector = new SecuritySelector({
            inputId: 'securitySelect',
            dropdownId: 'securityDropdown',
            symbolInputId: 'securitySymbol',
            apiPrefix: apiPrefix,
            enableHistory: true, // 启用搜索历史
            enableDeleteAll: true,
            onSelect: function(security) {
                // 保存当前选中证券的最小交易数量
                currentMinTradeQuantity = security.minTradeQuantity || null;
                // 保存当前选中证券的交易单位
                currentTradeUnit = security.tradeUnit || null;
                // 显示交易单位（单位为"手"时不显示，其他单位显示）
                if (currentTradeUnit && currentTradeUnit !== '手') {
                    $("#singleTradeQuantityUnit").text(currentTradeUnit).show();
                    $("#initialPositionUnit").text(currentTradeUnit).show();
                    $("#positionRangeMaxUnit").text(currentTradeUnit).show();
                } else {
                    $("#singleTradeQuantityUnit").hide();
                    $("#initialPositionUnit").hide();
                    $("#positionRangeMaxUnit").hide();
                }
                // 启用所有输入项
                enableAllInputs();
            },
            onClear: function() {
                // 清空交易单位
                currentTradeUnit = null;
                $("#singleTradeQuantityUnit").hide();
                $("#initialPositionUnit").hide();
                $("#positionRangeMaxUnit").hide();
                // 清空时禁用所有输入项
                disableAllInputs();
            }
        });
        securitySelector.init();
        
        // 初始化日期选择组件
        // 开始日期选择器：禁用今天（最大可选日期为昨天），禁用自动设置默认日期
        var yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        startDatePicker = new SecurityDatePicker({
            inputId: 'startDate',
            calendarId: 'startDateCalendar',
            apiPrefix: apiPrefix,
            maxDate: yesterday,  // 最大可选日期为昨天，即禁用今天
            autoInitDate: false,  // 禁用自动设置默认日期，由setDefaultDates统一设置
            onDateSelect: function(date) {
                console.log('开始日期选择:', date);
            }
        });
        startDatePicker.init();
        
        // 结束日期选择器：禁用今天（最大可选日期为昨天），禁用自动设置默认日期
        endDatePicker = new SecurityDatePicker({
            inputId: 'endDate',
            calendarId: 'endDateCalendar',
            apiPrefix: apiPrefix,
            maxDate: yesterday,  // 最大可选日期为昨天，即禁用今天
            autoInitDate: false,  // 禁用自动设置默认日期，由setDefaultDates统一设置
            onDateSelect: function(date) {
                console.log('结束日期选择:', date);
            }
        });
        endDatePicker.init();
        
        // 设置默认日期（延迟执行，确保日期选择器完全初始化后再设置）
        setTimeout(function() {
            // 先尝试恢复表单参数（如果是从同步页面返回的）
            var savedParams = sessionStorage.getItem('gridTradingBacktestFormParams');
            if (savedParams) {
                // 如果有保存的参数，恢复参数而不是设置默认日期
                restoreFormParams();
            } else {
                // 如果没有保存的参数，设置默认日期
                setDefaultDates();
            }
        }, 500);
        
        // 初始化：禁用所有输入项（因为还没有选择证券）
        disableAllInputs();
        
        // 涨跌类型变化时更新占位符和提示框
        $("#riseFallType").on('change', function() {
            if (!isSecuritySelected()) {
                $(this).val($(this).data('previous-value') || '1');
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            // 清空每上涨和每下跌的输入内容
            $("#riseValue").val('');
            $("#fallValue").val('');
            // 更新样式类（隐藏符号）
            updateInputClasses();
            // 隐藏提示框
            $("#riseValueTooltip").removeClass('show');
            $("#fallValueTooltip").removeClass('show');
            // 更新占位符
            updateTriggerPlaceholders();
        });
        
        // 保存涨跌类型的上一个值
        $("#riseFallType").on('focus', function() {
            $(this).data('previous-value', $(this).val());
        });
        
        // 初始化触发条件占位符
        updateTriggerPlaceholders();
        
        // 初始化输入框样式类
        updateInputClasses();
        
        // 初始基准价下拉箭头点击事件 - 只有点击箭头时才弹出下拉菜单
        $(".trigger-condition-dropdown-icon").on('click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            e.stopPropagation();
            var wrapper = $(this).closest('.trigger-condition-input-wrapper');
            var dropdown = wrapper.find('.trigger-condition-dropdown-menu');
            var isVisible = dropdown.hasClass('show');
            
            // 关闭所有下拉菜单
            $('.trigger-condition-dropdown-menu').removeClass('show');
            
            // 切换当前下拉菜单
            if (!isVisible) {
                dropdown.addClass('show');
            }
        });
        
        // 点击其他地方关闭下拉菜单
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.trigger-condition-input-wrapper').length) {
                $('.trigger-condition-dropdown-menu').removeClass('show');
            }
        });
        
        // 限制基准价只能输入数字和小数点，并更新提示框
        $("#initialBasePrice").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字和小数点
            var newValue = value.replace(/[^\d.]/g, '');
            // 只允许一个小数点
            var parts = newValue.split('.');
            if (parts.length > 2) {
                newValue = parts[0] + '.' + parts.slice(1).join('');
            }
            // 限制小数点后最多2位
            if (parts.length === 2 && parts[1].length > 2) {
                newValue = parts[0] + '.' + parts[1].substring(0, 2);
            }
            if (value !== newValue) {
                $(this).val(newValue);
            }
            // 实时更新涨幅/跌幅提示框（如果涨幅/跌幅输入框有值，则显示提示框）
            updateRiseValueTooltip(true);
            updateFallValueTooltip(true);
            // 更新初始市值提示
            updateInitialMarketValueTooltip(true);
        });
        
        // 基准价输入框点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#initialBasePrice").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 基准价输入框获得焦点事件
        $("#initialBasePrice").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 限制涨幅只能输入数字和小数点，并更新提示框
        $("#riseValue").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字和小数点
            var newValue = value.replace(/[^\d.]/g, '');
            // 只允许一个小数点
            var parts = newValue.split('.');
            if (parts.length > 2) {
                newValue = parts[0] + '.' + parts.slice(1).join('');
            }
            // 限制小数点后最多2位
            if (parts.length === 2 && parts[1].length > 2) {
                newValue = parts[0] + '.' + parts[1].substring(0, 2);
            }
            if (value !== newValue) {
                $(this).val(newValue);
            }
            // 更新样式类
            updateInputClasses();
            // 更新提示框（会在updateRiseValueTooltip中检查是否显示）
            updateRiseValueTooltip(true);
        });
        
        // 涨幅输入框点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#riseValue").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 涨幅输入框获得焦点时显示提示框
        $("#riseValue").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
            updateRiseValueTooltip(true);
        });
        
        // 涨幅输入框输入时更新提示框
        $("#riseValue").on('input', function() {
            if (isSecuritySelected()) {
                updateRiseValueTooltip(true);
            }
        });
        
        // 涨幅输入框失去焦点时自动格式化为两位小数
        $("#riseValue").on('blur', function(e) {
            // 检查是否点击的是增减按钮，如果是则不隐藏提示框
            var relatedTarget = e.relatedTarget || document.activeElement;
            if ($(relatedTarget).hasClass('trigger-condition-input-btn')) {
                return;
            }
            
            var value = $(this).val();
            if (value && value.trim() !== '') {
                var numValue = parseFloat(value);
                if (!isNaN(numValue) && numValue > 0) {
                    // 格式化为两位小数
                    $(this).val(numValue.toFixed(2));
                    // 更新提示框
                    if (isSecuritySelected()) {
                        updateRiseValueTooltip(true);
                    }
                }
            }
            
            setTimeout(function() {
                $("#riseValueTooltip").removeClass('show');
            }, 200);
            // 验证输入值
            if (isSecuritySelected()) {
                validateRiseFallValue('riseValue');
            }
        });
        
        // 跌幅输入框点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#fallValue").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 跌幅输入框获得焦点事件
        $("#fallValue").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
            updateFallValueTooltip(true);
        });
        
        // 限制跌幅只能输入数字和小数点
        $("#fallValue").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字和小数点
            var newValue = value.replace(/[^\d.]/g, '');
            // 只允许一个小数点
            var parts = newValue.split('.');
            if (parts.length > 2) {
                newValue = parts[0] + '.' + parts.slice(1).join('');
            }
            // 限制小数点后最多2位
            if (parts.length === 2 && parts[1].length > 2) {
                newValue = parts[0] + '.' + parts[1].substring(0, 2);
            }
            if (value !== newValue) {
                $(this).val(newValue);
            }
            // 更新样式类
            updateInputClasses();
            // 更新提示框
            updateFallValueTooltip(true);
        });
        
        // 跌幅输入框失去焦点时验证
        $("#fallValue").on('blur', function(e) {
            // 检查是否点击的是增减按钮，如果是则不隐藏提示框
            var relatedTarget = e.relatedTarget || document.activeElement;
            if ($(relatedTarget).hasClass('trigger-condition-input-btn')) {
                return;
            }
            
            setTimeout(function() {
                $("#fallValueTooltip").removeClass('show');
            }, 200);
            
            if (isSecuritySelected()) {
                validateRiseFallValue('fallValue');
            }
        });
        
        // 单笔数量输入框点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#singleTradeQuantity").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 单笔数量输入框获得焦点事件
        $("#singleTradeQuantity").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
            // 显示手数提示框
            updateHandsTooltip('singleTradeQuantity', 'singleTradeQuantityTooltip');
        });
        
        // 限制单笔交易数量只能输入数字（整数）
        $("#singleTradeQuantity").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字
            var newValue = value.replace(/[^\d]/g, '');
            if (value !== newValue) {
                $(this).val(newValue);
            }
            // 更新手数提示框
            updateHandsTooltip('singleTradeQuantity', 'singleTradeQuantityTooltip');
            // 更新倍数按钮高亮状态
            updateMultiplierButtonsHighlight();
            // 不在输入过程中验证，只在失去焦点时验证
        });
        
        // 单笔数量输入框失去焦点时验证
        $("#singleTradeQuantity").on('blur', function(e) {
            // 检查是否点击的是增减按钮，如果是则不处理
            var relatedTarget = e.relatedTarget || document.activeElement;
            if ($(relatedTarget).hasClass('trigger-condition-input-btn')) {
                return;
            }
            
            // 更新手数提示框（如果有值就显示，如果无值就隐藏）
            updateHandsTooltip('singleTradeQuantity', 'singleTradeQuantityTooltip');
            
            if (isSecuritySelected()) {
                validateSingleTradeQuantity();
                
                // 如果初始持仓为空，自动设置为单笔数量的10倍
                var initialPosition = $("#initialPosition").val();
                if (!initialPosition || initialPosition.trim() === '') {
                    var singleTradeQuantity = parseInt($("#singleTradeQuantity").val()) || 0;
                    if (singleTradeQuantity > 0) {
                        setInitialPositionMultiplier(10);
                    }
                } else {
                    // 更新倍数按钮高亮状态
                    updateMultiplierButtonsHighlight();
                }
            }
        });
        
        // 初始持仓输入框点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#initialPosition").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 初始持仓输入框获得焦点事件
        $("#initialPosition").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
            // 显示手数提示框
            updateHandsTooltip('initialPosition', 'initialPositionTooltip');
        });
        
        // 限制初始持仓只能输入数字（整数）
        $("#initialPosition").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字
            var newValue = value.replace(/[^\d]/g, '');
            if (value !== newValue) {
                $(this).val(newValue);
            }
            // 更新手数提示框
            updateHandsTooltip('initialPosition', 'initialPositionTooltip');
            // 更新倍数按钮高亮状态
            updateMultiplierButtonsHighlight();
            // 更新初始市值提示
            updateInitialMarketValueTooltip(true);
            // 不在输入过程中验证，只在失去焦点时验证
        });
        
        // 初始持仓输入框失去焦点时验证
        $("#initialPosition").on('blur', function(e) {
            // 检查是否点击的是增减按钮，如果是则不处理
            var relatedTarget = e.relatedTarget || document.activeElement;
            if ($(relatedTarget).hasClass('trigger-condition-input-btn')) {
                return;
            }
            
            // 更新手数提示框（如果有值就显示，如果无值就隐藏）
            updateHandsTooltip('initialPosition', 'initialPositionTooltip');
            // 更新初始市值提示
            updateInitialMarketValueTooltip(true);
            
            if (isSecuritySelected()) {
                validateInitialPosition();
                // 更新倍数按钮高亮状态
                updateMultiplierButtonsHighlight();
            }
        });
        
        // 初始可用资金输入框点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#initialAvailableFunds").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 初始可用资金输入框获得焦点事件
        $("#initialAvailableFunds").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 限制初始可用资金只能输入数字和小数点
        $("#initialAvailableFunds").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字和小数点
            var newValue = value.replace(/[^\d.]/g, '');
            // 只允许一个小数点
            var parts = newValue.split('.');
            if (parts.length > 2) {
                newValue = parts[0] + '.' + parts.slice(1).join('');
            }
            // 限制小数点后最多2位
            if (parts.length === 2 && parts[1].length > 2) {
                newValue = parts[0] + '.' + parts[1].substring(0, 2);
            }
            if (value !== newValue) {
                $(this).val(newValue);
            }
        });
        
        // 日期选择器点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#startDate, #endDate").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 日期选择器获得焦点事件
        $("#startDate, #endDate").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 涨跌类型下拉框点击事件
        $("#riseFallType").on('click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
        });
        
        // 涨跌类型下拉框获得焦点事件
        $("#riseFallType").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
        });
        
        // 涨跌类型下拉框变化事件
        $("#riseFallType").on('change', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
        });
        
        // 增减按钮点击事件
        $(".trigger-condition-input-btn").on('click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
        });
        
        // 初始基准价提示图标悬停事件
        $("#basePriceInfoIcon").on('mouseenter', function() {
            $("#basePriceInfoTooltip").addClass('show');
        });
        
        $("#basePriceInfoIcon").on('mouseleave', function() {
            $("#basePriceInfoTooltip").removeClass('show');
        });
        
        // 初始持仓提示图标悬停事件
        $("#initialPositionInfoIcon").on('mouseenter', function() {
            $("#initialPositionInfoTooltip").addClass('show');
        });
        
        $("#initialPositionInfoIcon").on('mouseleave', function() {
            $("#initialPositionInfoTooltip").removeClass('show');
        });
        
        // 初始可用资金提示图标悬停事件
        $("#initialAvailableFundsInfoIcon").on('mouseenter', function() {
            $("#initialAvailableFundsInfoTooltip").addClass('show');
        });
        
        $("#initialAvailableFundsInfoIcon").on('mouseleave', function() {
            $("#initialAvailableFundsInfoTooltip").removeClass('show');
        });
        
        // 高级设置输入框事件处理
        // 价格区间输入框
        $("#priceRangeMin, #priceRangeMax").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        $("#priceRangeMin, #priceRangeMax").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 限制价格区间只能输入数字和小数点
        $("#priceRangeMin, #priceRangeMax").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字和小数点
            var newValue = value.replace(/[^\d.]/g, '');
            // 只允许一个小数点
            var parts = newValue.split('.');
            if (parts.length > 2) {
                newValue = parts[0] + '.' + parts.slice(1).join('');
            }
            // 限制小数点后最多2位
            if (parts.length === 2 && parts[1].length > 2) {
                newValue = parts[0] + '.' + parts[1].substring(0, 2);
            }
            if (value !== newValue) {
                $(this).val(newValue);
            }
        });
        
        // 持仓范围输入框点击事件 - 使用mousedown确保在readonly状态下也能触发
        $("#positionRangeMin").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        $("#positionRangeMax").on('mousedown click', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
        });
        
        // 持仓范围输入框获得焦点事件
        $("#positionRangeMin").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
            // 显示手数提示框
            updateHandsTooltip('positionRangeMin', 'positionRangeMinTooltip');
        });
        
        $("#positionRangeMax").on('focus', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                $(this).blur();
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
            // 显示手数提示框
            updateHandsTooltip('positionRangeMax', 'positionRangeMaxTooltip');
        });
        
        // 限制持仓范围只能输入数字（整数）
        $("#positionRangeMin").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字
            var newValue = value.replace(/[^\d]/g, '');
            if (value !== newValue) {
                $(this).val(newValue);
            }
            // 更新手数提示框
            updateHandsTooltip('positionRangeMin', 'positionRangeMinTooltip');
            // 不在输入过程中验证，只在失去焦点时验证
        });
        
        $("#positionRangeMax").on('input', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                $.modal.msgWarning("请先选择证券标的");
                return;
            }
            var value = $(this).val();
            // 只允许数字
            var newValue = value.replace(/[^\d]/g, '');
            if (value !== newValue) {
                $(this).val(newValue);
            }
            // 更新手数提示框
            updateHandsTooltip('positionRangeMax', 'positionRangeMaxTooltip');
            // 不在输入过程中验证，只在失去焦点时验证
        });
        
        // 持仓范围输入框失去焦点时验证
        $("#positionRangeMin").on('blur', function(e) {
            // 检查是否点击的是增减按钮，如果是则不处理
            var relatedTarget = e.relatedTarget || document.activeElement;
            if ($(relatedTarget).hasClass('trigger-condition-input-btn')) {
                return;
            }
            
            // 更新手数提示框（如果有值就显示，如果无值就隐藏）
            updateHandsTooltip('positionRangeMin', 'positionRangeMinTooltip');
            
            if (isSecuritySelected()) {
                validatePositionRangeMin();
            }
        });
        
        $("#positionRangeMax").on('blur', function(e) {
            // 检查是否点击的是增减按钮，如果是则不处理
            var relatedTarget = e.relatedTarget || document.activeElement;
            if ($(relatedTarget).hasClass('trigger-condition-input-btn')) {
                return;
            }
            
            // 更新手数提示框（如果有值就显示，如果无值就隐藏）
            updateHandsTooltip('positionRangeMax', 'positionRangeMaxTooltip');
            
            if (isSecuritySelected()) {
                validatePositionRangeMax();
            }
        });
        
        // 倍数委托开关
        $("#multiplierOrder").on('change', function(e) {
            if (!isSecuritySelected()) {
                e.preventDefault();
                e.stopPropagation();
                // 如果未选择证券，恢复开关状态
                $(this).prop('checked', !$(this).prop('checked'));
                $.modal.msgWarning("请先选择证券标的");
                return false;
            }
            // 开关状态改变时的处理逻辑
            var isChecked = $(this).prop('checked');
            console.log('倍数委托开关状态:', isChecked);
        });
        
        // 自定义倍数模态框事件处理
        // ESC键关闭模态框
        $(document).on('keydown', function(e) {
            if (e.keyCode === 27) { // ESC键
                if ($("#customMultiplierModal").is(':visible')) {
                    hideCustomMultiplierModal();
                }
                if ($("#customAvailableFundsMultiplierModal").is(':visible')) {
                    hideCustomAvailableFundsMultiplierModal();
                }
            }
        });
    });
    
    // 初始化图表
    function initChart() {
        var chartDom = document.getElementById('profit-chart');
        profitChart = echarts.init(chartDom);
        
        // 监听窗口大小变化，自动调整图表大小
        window.addEventListener('resize', function() {
            if (profitChart) {
                profitChart.resize();
            }
        });
        
        // 确保图表容器有足够的宽度
        if (chartDom) {
            chartDom.style.minWidth = '800px';
        }
    }
    
    // 设置默认日期（默认填充近1年）
    function setDefaultDates() {
        var today = new Date();
        var yesterday = new Date(today);
        yesterday.setDate(today.getDate() - 1);
        var oneYearAgo = new Date();
        oneYearAgo.setMonth(today.getMonth() - 12);
        
        var endDateStr = yesterday.toISOString().split('T')[0];
        var startDateStr = oneYearAgo.toISOString().split('T')[0];
        
        // 查找最近的交易日
        var nearestEndDate = endDateStr;
        var nearestStartDate = startDateStr;
        
        if (endDatePicker && endDatePicker.findNearestTradingDay) {
            nearestEndDate = endDatePicker.findNearestTradingDay(endDateStr);
        }
        
        if (startDatePicker && startDatePicker.findNearestTradingDay) {
            nearestStartDate = startDatePicker.findNearestTradingDay(startDateStr);
        }
        
        if (endDatePicker) {
            endDatePicker.setDate(nearestEndDate);
        } else {
            $("#endDate").val(nearestEndDate);
        }
        
        if (startDatePicker) {
            startDatePicker.setDate(nearestStartDate);
        } else {
            $("#startDate").val(nearestStartDate);
        }
        
        // 高亮"近1年"按钮（默认选择）
        updateDateRangeButtonsHighlight(12);
    }
    
    // 设置日期范围（根据月份数）
    function setDateRange(months) {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        
        var today = new Date();
        var yesterday = new Date(today);
        yesterday.setDate(today.getDate() - 1);
        var startDate = new Date();
        startDate.setMonth(today.getMonth() - months);
        
        var endDateStr = yesterday.toISOString().split('T')[0];
        var startDateStr = startDate.toISOString().split('T')[0];
        
        // 查找最近的交易日
        var nearestEndDate = endDateStr;
        var nearestStartDate = startDateStr;
        
        if (endDatePicker && endDatePicker.findNearestTradingDay) {
            nearestEndDate = endDatePicker.findNearestTradingDay(endDateStr);
        }
        
        if (startDatePicker && startDatePicker.findNearestTradingDay) {
            nearestStartDate = startDatePicker.findNearestTradingDay(startDateStr);
        }
        
        if (endDatePicker) {
            endDatePicker.setDate(nearestEndDate);
        } else {
            $("#endDate").val(nearestEndDate);
        }
        
        if (startDatePicker) {
            startDatePicker.setDate(nearestStartDate);
        } else {
            $("#startDate").val(nearestStartDate);
        }
        
        // 更新按钮高亮状态
        updateDateRangeButtonsHighlight(months);
    }
    
    // 更新日期范围按钮高亮状态
    function updateDateRangeButtonsHighlight(selectedMonths) {
        $(".date-range-btn").each(function() {
            var btn = $(this);
            var btnText = btn.text();
            var btnMonths = 0;
            
            if (btnText === '近1月') {
                btnMonths = 1;
            } else if (btnText === '近3月') {
                btnMonths = 3;
            } else if (btnText === '近半年') {
                btnMonths = 6;
            } else if (btnText === '近1年') {
                btnMonths = 12;
            } else if (btnText === '近2年') {
                btnMonths = 24;
            }
            
            if (btnMonths > 0) {
                if (btnMonths === selectedMonths) {
                    btn.addClass('active');
                } else {
                    btn.removeClass('active');
                }
            }
        });
    }
    
    // 加载证券列表
    function loadSecuritiesList() {
        $.ajax({
            url: ctx + "security/securities",
            type: "GET",
            dataType: 'json',
            success: function(data) {
                if (data.code === 0 && data.data) {
                    securitiesList = data.data;
                }
            },
            error: function(xhr, status, error) {
                console.error("获取证券列表失败:", error);
            }
        });
    }
    
    // 显示证券下拉框
    function showSecurityDropdown(searchText) {
        var dropdown = $("#securityDropdown");
        dropdown.empty();
        
        var filteredSecurities = securitiesList.filter(function(security) {
            var code = (security.code || '').toLowerCase();
            var name = (security.name || '').toLowerCase();
            var fullCode = (security.exchange + security.code).toLowerCase();
            var search = searchText.toLowerCase();
            return code.includes(search) || name.includes(search) || fullCode.includes(search);
        });
        
        if (filteredSecurities.length > 0) {
            filteredSecurities.forEach(function(security) {
                var displayCode = security.exchange + security.code;
                var displayText = displayCode + " - " + security.name;
                
                var item = $('<div class="dropdown-item">' +
                    '<strong>' + displayCode + '</strong> - ' + security.name + '</div>');
                
                item.hover(
                    function() { $(this).css('background-color', '#f5f5f5'); },
                    function() { $(this).css('background-color', 'white'); }
                );
                
                item.on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $("#securitySelect").val(displayText);
                    $("#securitySymbol").val(displayCode);
                    // 保存当前选中证券的最小交易数量
                    currentMinTradeQuantity = security.minTradeQuantity || null;
                    hideSecurityDropdown();
                    // 启用所有输入项
                    enableAllInputs();
                    return false;
                });
                
                dropdown.append(item);
            });
            dropdown.show();
        } else {
            dropdown.hide();
        }
    }
    
    // 隐藏证券下拉框
    function hideSecurityDropdown() {
        $("#securityDropdown").hide();
        currentSelectedIndex = -1;
    }
    
    // 更新选中项的高亮显示
    function updateSelection(items) {
        items.removeClass('selected');
        if (currentSelectedIndex >= 0 && currentSelectedIndex < items.length) {
            items.eq(currentSelectedIndex).addClass('selected');
        }
    }
    
    // 开始回测
    function startBacktest() {
        var symbol = $("#securitySymbol").val();
        var startDate = startDatePicker ? startDatePicker.getSelectedDate() : $("#startDate").val();
        var endDate = endDatePicker ? endDatePicker.getSelectedDate() : $("#endDate").val();
        
        if (!symbol) {
            $.modal.msgWarning("请选择证券");
            return;
        }
        
        if (!startDate || !endDate) {
            $.modal.msgWarning("请选择回测日期范围");
            return;
        }
        
        if (new Date(startDate) > new Date(endDate)) {
            $.modal.msgWarning("开始日期不能大于结束日期");
            return;
        }
        
        // 验证必填字段
        var initialBasePrice = parseFloat($("#initialBasePrice").val());
        if (!initialBasePrice || initialBasePrice <= 0) {
            $.modal.msgWarning("请输入初始基准价");
            return;
        }
        
        // 验证每上涨值
        var riseValueInput = $("#riseValue").val();
        if (!riseValueInput || riseValueInput.trim() === '') {
            $.modal.msgWarning("每上涨不能为空");
            $("#riseValue").focus();
            return;
        }
        var riseValue = parseFloat(riseValueInput);
        if (isNaN(riseValue) || riseValue <= 0) {
            $.modal.msgWarning("每上涨值必须大于0");
            $("#riseValue").focus();
            return;
        }
        
        // 验证每下跌值
        var fallValueInput = $("#fallValue").val();
        if (!fallValueInput || fallValueInput.trim() === '') {
            $.modal.msgWarning("每下跌不能为空");
            $("#fallValue").focus();
            return;
        }
        var fallValue = parseFloat(fallValueInput);
        if (isNaN(fallValue) || fallValue <= 0) {
            $.modal.msgWarning("每下跌值必须大于0");
            $("#fallValue").focus();
            return;
        }
        
        var singleTradeQuantity = parseInt($("#singleTradeQuantity").val());
        if (!singleTradeQuantity || singleTradeQuantity <= 0) {
            $.modal.msgWarning("请输入单笔数量");
            return;
        }
        
        var initialPosition = parseInt($("#initialPosition").val());
        if (!initialPosition || initialPosition <= 0) {
            $.modal.msgWarning("请输入初始持仓");
            return;
        }
        
        // 先校验数据完整性
        validateDataCompleteness(symbol, startDate, endDate, function() {
            // 数据完整，继续执行回测
            executeBacktest(symbol, startDate, endDate);
        });
    }
    
    // 校验数据完整性
    function validateDataCompleteness(symbol, startDate, endDate, callback) {
        // 显示加载状态
        $("#loading-area").show();
        $("#results-area").hide();
        $("#error-area").hide();
        $("#no-data-area").hide();
        
        // 调用数据完整性校验接口
        $.ajax({
            url: ctx + "security/time-share/invalid-dates",
            type: "GET",
            data: {
                symbol: symbol,
                startDate: startDate,
                endDate: endDate
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 0 && data.data) {
                    var invalidDates = data.data;
                    
                    if (invalidDates && invalidDates.length > 0) {
                        // 数据不完整，显示确认弹窗
                        $("#loading-area").hide();
                        var errorMsg = "证券[" + symbol + "]数据校验失败，缺失数据的交易日：" + invalidDates.join(", ");
                        showSyncDataModal(errorMsg, symbol, startDate, endDate);
                    } else {
                        // 数据完整，执行回调
                        callback();
                    }
                } else {
                    // 校验接口调用失败，仍然尝试回测（兼容旧逻辑）
                    console.warn("数据完整性校验失败，继续执行回测:", data.msg);
                    callback();
                }
            },
            error: function(xhr, status, error) {
                // 校验接口调用失败，仍然尝试回测（兼容旧逻辑）
                console.error("数据完整性校验接口调用失败:", error);
                callback();
            }
        });
    }
    
    // 执行回测
    function executeBacktest(symbol, startDate, endDate) {
        // 显示加载状态
        $("#loading-area").show();
        $("#results-area").hide();
        $("#error-area").hide();
        $("#no-data-area").hide();
        
        // 重新获取参数值（确保在函数作用域内）
        var initialBasePrice = parseFloat($("#initialBasePrice").val());
        var riseValue = parseFloat($("#riseValue").val());
        var fallValue = parseFloat($("#fallValue").val());
        var singleTradeQuantity = parseInt($("#singleTradeQuantity").val());
        var initialPosition = parseInt($("#initialPosition").val());
        
        // 构建回测参数
        var backtestParam = {
            symbol: symbol,
            backtestPeriod: {
                startDate: startDate,
                endDate: endDate
            },
            triggerCondition: {
                riseFallType: $("#riseFallType").val(),
                initialBenchmarkPrice: initialBasePrice,
                perRiseValue: riseValue,
                perFallValue: fallValue
            },
            mandateSettings: {
                initialPosition: initialPosition,
                mandateQuantity: {
                    singleBuyQuantity: singleTradeQuantity,
                    singleSellQuantity: singleTradeQuantity
                },
                benchmarkPriceUpdateType: "1" // 默认按触发价格
            }
        };
        
        // 初始可用资金（可选）
        var initialAvailableFunds = $("#initialAvailableFunds").val();
        if (initialAvailableFunds && initialAvailableFunds.trim() !== '') {
            var funds = parseFloat(initialAvailableFunds);
            if (funds > 0) {
                backtestParam.mandateSettings.initialAvailableAmount = funds;
            }
        }
        
        // 高级设置（可选）
        var advancedSetting = {};
        var hasAdvancedSetting = false;
        
        // 价格区间（可选）
        var priceRangeMin = $("#priceRangeMin").val();
        var priceRangeMax = $("#priceRangeMax").val();
        if ((priceRangeMin && priceRangeMin.trim() !== '') || (priceRangeMax && priceRangeMax.trim() !== '')) {
            advancedSetting.priceRange = {};
            if (priceRangeMin && priceRangeMin.trim() !== '') {
                var minPrice = parseFloat(priceRangeMin);
                if (minPrice > 0) {
                    advancedSetting.priceRange.priceFloor = minPrice;
                    hasAdvancedSetting = true;
                }
            }
            if (priceRangeMax && priceRangeMax.trim() !== '') {
                var maxPrice = parseFloat(priceRangeMax);
                if (maxPrice > 0) {
                    advancedSetting.priceRange.priceCeiling = maxPrice;
                    hasAdvancedSetting = true;
                }
            }
        }
        
        // 持仓范围（可选）
        var positionRangeMin = $("#positionRangeMin").val();
        var positionRangeMax = $("#positionRangeMax").val();
        if ((positionRangeMin && positionRangeMin.trim() !== '') || (positionRangeMax && positionRangeMax.trim() !== '')) {
            advancedSetting.positionRange = {};
            if (positionRangeMin && positionRangeMin.trim() !== '') {
                var minPosition = parseInt(positionRangeMin);
                if (minPosition > 0) {
                    advancedSetting.positionRange.positionFloor = minPosition;
                    hasAdvancedSetting = true;
                }
            }
            if (positionRangeMax && positionRangeMax.trim() !== '') {
                var maxPosition = parseInt(positionRangeMax);
                if (maxPosition > 0) {
                    advancedSetting.positionRange.positionCeiling = maxPosition;
                    hasAdvancedSetting = true;
                }
            }
        }
        
        // 倍数委托开关（可选）
        var multiplierOrder = $("#multiplierOrder").is(':checked');
        if (multiplierOrder) {
            advancedSetting.multipleMandateSwitch = true;
            hasAdvancedSetting = true;
        }
        
        if (hasAdvancedSetting) {
            backtestParam.advancedSetting = advancedSetting;
        }
        
        // 手续费设置（必填）
        var commissionTenThousandth = $("#commissionTenThousandth").val();
        if (!commissionTenThousandth || commissionTenThousandth.trim() === '') {
            $.modal.msgWarning("请输入佣金万几");
            $("#commissionTenThousandth").focus();
            return;
        }
        var commissionValue = parseFloat(commissionTenThousandth);
        if (isNaN(commissionValue) || commissionValue <= 0) {
            $.modal.msgWarning("佣金万几必须大于0");
            $("#commissionTenThousandth").focus();
            return;
        }
        
        var freeMinimumCommission = $("#freeMinimumCommission").is(':checked');
        
        backtestParam.tradeCharge = {
            commissionTenThousandth: commissionValue,
            freeMinimumCommission: freeMinimumCommission
        };
        
        // 发送回测请求
        $.ajax({
            url: prefix + "/backtest",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(backtestParam),
            dataType: 'json',
            success: function(data) {
                $("#loading-area").hide();
                if (data.code === 0 && data.data) {
                    displayBacktestResults(data.data);
                    $("#results-area").show();
                    $("#error-area").hide();
                } else {
                    // 使用弹窗显示错误信息
                    var errorMsg = data.msg || "回测失败";
                    $.modal.alertError(errorMsg);
                    $("#error-area").hide();
                    $("#results-area").hide();
                }
            },
            error: function(xhr, status, error) {
                $("#loading-area").hide();
                var errorMsg = "回测请求失败";
                
                // 尝试从响应中获取错误信息
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.msg) {
                        errorMsg = xhr.responseJSON.msg;
                    } else if (xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                } else if (xhr.responseText) {
                    try {
                        var response = JSON.parse(xhr.responseText);
                        if (response.msg) {
                            errorMsg = response.msg;
                        } else if (response.message) {
                            errorMsg = response.message;
                        }
                    } catch (e) {
                        // 如果无法解析JSON，使用默认错误信息
                        if (xhr.status === 0) {
                            errorMsg = "网络连接失败，请检查网络设置";
                        } else if (xhr.status === 404) {
                            errorMsg = "请求的接口不存在";
                        } else if (xhr.status === 500) {
                            errorMsg = "服务器内部错误，请联系管理员";
                        } else {
                            errorMsg = "回测请求失败: " + (error || "未知错误");
                        }
                    }
                } else {
                    // 根据HTTP状态码设置错误信息
                    if (xhr.status === 0) {
                        errorMsg = "网络连接失败，请检查网络设置";
                    } else if (xhr.status === 404) {
                        errorMsg = "请求的接口不存在";
                    } else if (xhr.status === 500) {
                        errorMsg = "服务器内部错误，请联系管理员";
                    } else {
                        errorMsg = "回测请求失败: " + (error || "未知错误");
                    }
                }
                
                // 使用弹窗显示错误信息
                $.modal.alertError(errorMsg);
                $("#error-area").hide();
                $("#results-area").hide();
            }
        });
    }
    
    // 显示回测结果
    function displayBacktestResults(result) {
        // 从交易统计中获取数据
        var tradingStats = result || {};
        
        // 显示回测结果数据
        var gridProfitRate = tradingStats.totalProfitRateByInitialTotalAssets || 0;
        var stockRiseRate = tradingStats.alwaysHoldProfitRate || 0;
        var excessProfitRate = tradingStats.excessProfitRateByInitialTotalAssets || 0;
        
        // 移除之前的样式类
        $("#gridProfitRate").removeClass('positive negative').text(formatPercent(gridProfitRate));
        if (gridProfitRate >= 0) {
            $("#gridProfitRate").addClass('positive');
        } else {
            $("#gridProfitRate").addClass('negative');
        }
        
        $("#stockRiseRate").removeClass('positive negative').text(formatPercent(stockRiseRate));
        if (stockRiseRate >= 0) {
            $("#stockRiseRate").addClass('positive');
        } else {
            $("#stockRiseRate").addClass('negative');
        }
        
        $("#excessProfitRate").removeClass('positive negative').text(formatPercent(excessProfitRate));
        if (excessProfitRate >= 0) {
            $("#excessProfitRate").addClass('positive');
        } else {
            $("#excessProfitRate").addClass('negative');
        }
        
        $("#initialTotalAssets").text(formatNumber(result.initialTotalAssets || 0));
        $("#finalTotalAssets").text(formatNumber(tradingStats.totalAssets || 0));
        $("#tradeCost").text(formatNumber(tradingStats.tradeCharge || 0));
        $("#buyCount").text(tradingStats.buyCount || 0);
        $("#sellCount").text(tradingStats.sellCount || 0);
        
        // 从每日交易明细中提取收益走势数据
        var profitTrend = [];
        
        if (result.dayDetailList && result.dayDetailList.length > 0) {
            // 遍历每日交易明细，构建收益走势数据
            result.dayDetailList.forEach(function(dayDetail) {
                if (dayDetail.date) {
                    // DayDetail继承自SecurityGridTradingBacktestResultTradingStatisticsDto，统计信息直接在dayDetail对象下
                    profitTrend.push({
                        date: dayDetail.date,
                        gridProfitRate: dayDetail.totalProfitRateByInitialTotalAssets || 0,
                        stockProfitRate: dayDetail.alwaysHoldProfitRate || 0,
                        totalProfitRate: dayDetail.totalProfitRateByInitialTotalAssets || 0,
                        alwaysHoldProfitRate: dayDetail.alwaysHoldProfitRate || 0
                    });
                }
            });
        }
        
        // 使用后端返回的最大回撤数据（从交易统计中获取）
        var maxDrawdown = tradingStats.maxDrawdownRatioByInitialTotalAssets || 0;
        $("#maxDrawdown").removeClass('positive negative').text(formatPercent(maxDrawdown)).addClass('negative');
        
        // 绘制收益率走势图
        if (profitTrend && profitTrend.length > 0) {
            drawProfitChart(profitTrend);
        } else {
            // 如果没有走势数据，显示提示
            if (profitChart) {
                profitChart.clear();
            }
            $("#profit-chart").html('<div class="no-data">暂无收益率走势数据</div>');
        }
        
        // 显示交易明细
        displayTransactionDetails(result);
    }
    
    // 交易明细排序状态
    var transactionSortOrder = 'desc'; // 'asc' 或 'desc'
    
    // 显示交易明细
    function displayTransactionDetails(result) {
        var detailsList = $("#transactionDetailsList");
        detailsList.empty();
        
        if (!result.dayDetailList || result.dayDetailList.length === 0) {
            detailsList.html('<div class="no-data">暂无交易明细</div>');
            return;
        }
        
        // 保存原始数据，用于排序
        window.transactionDetailsData = result.dayDetailList;
        
        // 创建汇总表格
        var summaryTable = $('<table class="transaction-table"></table>');
        var thead = $('<thead><tr>' +
            '<th>日期 <span class="sort-icon" onclick="sortTransactionDetails()" id="sortIcon">▼</span></th>' +
            '<th>买入/卖出</th>' +
            '<th>股数/市值</th>' +
            '<th>现金/总资产</th>' +
            '<th>累计收益</th>' +
            '</tr></thead>');
        
        var tbody = $('<tbody></tbody>');
        
        // 遍历每日数据，生成汇总表格
        result.dayDetailList.forEach(function(dayDetail, index) {
            // DayDetail继承自SecurityGridTradingBacktestResultTradingStatisticsDto，统计信息直接在dayDetail对象下
            var dayStats = dayDetail || {};
            
            // 持仓数量
            var position = dayStats.position || 0;
            // 市值
            var marketValue = dayStats.marketValue || 0;
            // 可用资金
            var availableAmount = dayStats.availableAmount;
            var availableAmountDisplay = (availableAmount == null || availableAmount === undefined) ? 'N/A' : formatNumber(availableAmount);
            // 总资产
            var totalAsset = dayStats.totalAssets || 0;
            // 累计收益率
            var totalProfitRate = dayStats.totalProfitRateByInitialTotalAssets || 0;
            // 累计收益金额
            var totalProfit = dayStats.totalProfit || 0;
            // 买入数量
            var buyQuantity = dayStats.buyQuantity || 0;
            // 卖出数量
            var sellQuantity = dayStats.sellQuantity || 0;
            
            // 判断收益正负，设置颜色
            var profitRateClass = totalProfitRate >= 0 ? 'profit-positive' : 'profit-negative';
            var profitAmountClass = totalProfit >= 0 ? 'profit-positive' : 'profit-negative';
            
            // 日期列：包含日期和展开/折叠图标
            var hasDetails = dayDetail.details && dayDetail.details.length > 0;
            
            var row = $('<tr></tr>');
            
            // 创建展开/折叠图标
            var expandIconHtml = '';
            if (hasDetails) {
                expandIconHtml = '<span class="expand-icon" onclick="toggleDetailTable(' + index + ')" id="expandIcon' + index + '">▼</span>';
            } else {
                expandIconHtml = '<span style="color: #ccc;">-</span>';
            }
            
            row.append('<td class="date-cell">' + (dayDetail.date || '') + ' ' + expandIconHtml + '</td>');
            
            // 买入/卖出数量列
            row.append('<td class="value-cell">' + 
                '<span class="trade-type-buy">买入: ' + buyQuantity + '</span><br/>' +
                '<span class="trade-type-sell">卖出: ' + sellQuantity + '</span>' +
                '</td>');
            
            row.append('<td class="value-cell">' + position + '<br/>' + formatNumber(marketValue) + '</td>');
            row.append('<td class="value-cell">' + availableAmountDisplay + '<br/>' + formatNumber(totalAsset) + '</td>');
            row.append('<td class="value-cell">' +
                '<span class="' + profitRateClass + '">' + formatPercent(totalProfitRate) + '</span><br/>' +
                '<span class="' + profitAmountClass + '">' + formatNumber(totalProfit) + '</span>' +
                '</td>');
            
            tbody.append(row);
            
            // 如果有详细交易记录，创建详细表格（默认隐藏）
            if (hasDetails) {
                var detailTable = $('<table class="detail-transaction-table" id="detailTable' + index + '"></table>');
                var detailThead = $('<thead><tr>' +
                    '<th>时间</th>' +
                    '<th>价格</th>' +
                    '<th>数量</th>' +
                    '<th>持仓</th>' +
                    '<th>手续费</th>' +
                    '</tr></thead>');
                
                var detailTbody = $('<tbody></tbody>');
                
                dayDetail.details.forEach(function(detail) {
                    var isBuy = (detail.type === 'buy' || detail.type === 'BUY' || detail.type === '买' || detail.type === '买入');
                    var iconClass = isBuy ? 'trade-icon-buy' : 'trade-icon-sell';
                    var iconText = isBuy ? '买' : '卖';
                    
                    var detailRow = $('<tr>' +
                        '<td class="time-cell">' +
                        '<span class="trade-icon ' + iconClass + '">' + iconText + '</span>' +
                        (detail.time || '') +
                        '</td>' +
                        '<td>' + formatNumber(detail.price || 0) + '</td>' +
                        '<td>' + (detail.quantity || 0) + '</td>' +
                        '<td>' + (detail.position || 0) + '</td>' +
                        '<td>' + formatNumber(detail.charge || 0) + '</td>' +
                        '</tr>');
                    detailTbody.append(detailRow);
                });
                
                detailTable.append(detailThead).append(detailTbody);
                
                // 将详细表格添加到对应行的下一行
                var detailRow = $('<tr id="detailRow' + index + '" style="display: none;"><td colspan="5" style="padding: 10px; background: #f8f9fa;"></td></tr>');
                detailRow.find('td').append(detailTable);
                tbody.append(detailRow);
            }
        });
        
        summaryTable.append(thead).append(tbody);
        detailsList.append(summaryTable);
        
        // 添加表格底部统计
        var footer = $('<div style="text-align: center; padding: 10px; color: #666; font-size: 13px;">共有' + result.dayDetailList.length + '条记录</div>');
        detailsList.append(footer);
        
        // 自动展开交易明细容器
        var content = $("#transactionDetailsContent");
        var toggle = $("#transactionDetailsToggle");
        if (!content.hasClass('expanded')) {
            content.addClass('expanded');
            toggle.text('收起 ▲');
        }
    }
    
    // 按日期排序交易明细
    function sortTransactionDetails() {
        if (!window.transactionDetailsData || window.transactionDetailsData.length === 0) {
            return;
        }
        
        // 切换排序顺序
        transactionSortOrder = transactionSortOrder === 'asc' ? 'desc' : 'asc';
        
        // 复制数组并排序
        var sortedData = window.transactionDetailsData.slice();
        sortedData.sort(function(a, b) {
            var dateA = a.date || '';
            var dateB = b.date || '';
            if (transactionSortOrder === 'asc') {
                return dateA.localeCompare(dateB);
            } else {
                return dateB.localeCompare(dateA);
            }
        });
        
        // 更新排序图标
        var sortIcon = $("#sortIcon");
        sortIcon.text(transactionSortOrder === 'asc' ? '▲' : '▼');
        
        // 重新构建表格，保留原始数据引用
        var tempResult = {
            dayDetailList: sortedData
        };
        // 更新全局数据引用
        window.transactionDetailsData = sortedData;
        displayTransactionDetails(tempResult);
    }
    
    // 切换详细交易记录显示/隐藏
    function toggleDetailTable(index) {
        var detailRow = $("#detailRow" + index);
        var expandIcon = $("#expandIcon" + index);
        
        // 调试：输出索引和元素
        console.log('切换详细表格，索引:', index);
        console.log('详细行元素:', detailRow.length);
        console.log('展开图标元素:', expandIcon.length);
        
        if (detailRow.length === 0) {
            console.error('找不到详细行元素，索引:', index);
            return;
        }
        
        if (detailRow.is(':visible')) {
            detailRow.hide();
            if (expandIcon.length > 0) {
                expandIcon.text('▼');
            }
        } else {
            // 隐藏其他已展开的详细表格
            $('[id^="detailRow"]').hide();
            $('[id^="expandIcon"]').text('▼');
            
            detailRow.show();
            if (expandIcon.length > 0) {
                expandIcon.text('▲');
            }
        }
    }
    
    // 切换交易明细显示/隐藏
    function toggleTransactionDetails() {
        var content = $("#transactionDetailsContent");
        var toggle = $("#transactionDetailsToggle");
        
        if (content.hasClass('expanded')) {
            content.removeClass('expanded');
            toggle.text('展开 ▼');
        } else {
            content.addClass('expanded');
            toggle.text('收起 ▲');
        }
    }
    
    // 切换日期分组显示/隐藏
    function toggleDateGroup(index) {
        var content = $("#dateGroupContent" + index);
        var toggle = $("#dateGroupToggle" + index);
        
        if (content.hasClass('expanded')) {
            content.removeClass('expanded');
            toggle.text('展开 ▼');
        } else {
            content.addClass('expanded');
            toggle.text('收起 ▲');
        }
    }
    
    // 绘制收益率走势图
    function drawProfitChart(profitTrend) {
        // 准备数据
        var dates = profitTrend.map(function(item) {
            return item.date || item.time || item.minute || '';
        });
        
        var gridProfitData = profitTrend.map(function(item) {
            return parseFloat(item.gridProfitRate || item.totalProfitRate || 0);
        });
        
        var stockProfitData = profitTrend.map(function(item) {
            return parseFloat(item.stockProfitRate || item.alwaysHoldProfitRate || 0);
        });
        
        // 调试：输出数据长度
        console.log('收益走势数据点数量:', profitTrend.length);
        console.log('日期数组长度:', dates.length);
        console.log('网格收益率数据长度:', gridProfitData.length);
        console.log('个股同期涨幅数据长度:', stockProfitData.length);
        
        // 获取回测结束日期的数据（最后一天的数据）
        var finalGridProfitRate = gridProfitData.length > 0 ? gridProfitData[gridProfitData.length - 1] : 0;
        var finalStockProfitRate = stockProfitData.length > 0 ? stockProfitData[stockProfitData.length - 1] : 0;
        
        // 构建系列数据
        var series = [
            {
                name: '网格收益率',
                type: 'line',
                smooth: false,
                data: gridProfitData,
                itemStyle: {
                    color: '#007bff'
                },
                lineStyle: {
                    width: 2
                },
                symbol: 'circle',
                symbolSize: 4,
                showSymbol: false
            },
            {
                name: '个股同期涨幅',
                type: 'line',
                smooth: false,
                data: stockProfitData,
                itemStyle: {
                    color: '#28a745'
                },
                lineStyle: {
                    width: 2
                },
                symbol: 'circle',
                symbolSize: 4,
                showSymbol: false
            }
        ];
        
        var option = {
            title: {
                text: '回测收益率走势',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    var result = params[0].name + '<br/>';
                    params.forEach(function(param) {
                        result += param.marker + param.seriesName + ': ' + formatPercent(param.value) + '<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: [
                    '网格收益率 ' + formatPercent(finalGridProfitRate),
                    '个股同期涨幅 ' + formatPercent(finalStockProfitRate)
                ],
                top: 30
            },
            grid: {
                left: '5%',
                right: '5%',
                bottom: '25%',
                top: '12%',
                containLabel: false
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 0,
                    end: 100,
                    xAxisIndex: [0],
                    filterMode: 'none'
                },
                {
                    type: 'slider',
                    start: 0,
                    end: 100,
                    height: 40,
                    bottom: 10,
                    xAxisIndex: [0],
                    showDetail: true,
                    showDataShadow: 'auto',
                    realtime: true
                }
            ],
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: dates,
                axisLabel: {
                    rotate: 45,
                    interval: function(index) {
                        // 如果数据点太多，自动间隔显示
                        var total = dates.length;
                        if (total <= 10) {
                            return 0; // 10个以内全部显示
                        } else if (total <= 30) {
                            return index % 2 === 0 ? 0 : 1; // 每2个显示1个
                        } else if (total <= 60) {
                            return index % 3 === 0 ? 0 : 1; // 每3个显示1个
                        } else {
                            return index % Math.ceil(total / 20) === 0 ? 0 : 1; // 最多显示20个标签
                        }
                    },
                    formatter: function(value) {
                        // 格式化日期显示
                        if (value && value.length > 10) {
                            return value.substring(5); // 只显示月-日
                        }
                        return value;
                    },
                    fontSize: 11
                },
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: function(value) {
                        return formatPercent(value);
                    }
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            },
            series: series
        };
        
        // 设置图表配置
        profitChart.setOption(option, true);
        
        // 确保图表正确渲染
        setTimeout(function() {
            if (profitChart) {
                profitChart.resize();
            }
        }, 100);
    }
    
    // 格式化百分比
    function formatPercent(value) {
        if (value == null || value === undefined) return '--';
        return (parseFloat(value) || 0).toFixed(2) + '%';
    }
    
    // 格式化数字
    function formatNumber(value) {
        if (value == null || value === undefined) return '--';
        return (parseFloat(value) || 0).toLocaleString('zh-CN', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }
    
    // 更新触发条件占位符和样式
    function updateTriggerPlaceholders() {
        var riseFallType = $("#riseFallType").val();
        var riseInput = $("#riseValue");
        var fallInput = $("#fallValue");
        
        if (riseFallType === "1") {
            // 按百分比
            riseInput.attr("placeholder", "涨幅(%)");
            fallInput.attr("placeholder", "跌幅(%)");
        } else {
            // 按差价
            riseInput.attr("placeholder", "涨幅(元)");
            fallInput.attr("placeholder", "跌幅(元)");
        }
        // 更新样式类
        updateInputClasses();
    }
    
    // 更新输入框样式类
    function updateInputClasses() {
        var riseFallType = $("#riseFallType").val();
        var riseInput = $("#riseValue");
        var fallInput = $("#fallValue");
        var riseSymbolBefore = $("#riseValueSymbolBefore");
        var riseSymbolAfter = $("#riseValueSymbolAfter");
        var fallSymbolBefore = $("#fallValueSymbolBefore");
        var fallSymbolAfter = $("#fallValueSymbolAfter");
        
        if (riseFallType === "1") {
            // 按百分比：如果有值，显示符号
            if (riseInput.val() && riseInput.val().trim() !== '') {
                riseSymbolBefore.addClass("show");
                riseSymbolAfter.addClass("show");
            } else {
                riseSymbolBefore.removeClass("show");
                riseSymbolAfter.removeClass("show");
            }
            if (fallInput.val() && fallInput.val().trim() !== '') {
                fallSymbolBefore.addClass("show");
                fallSymbolAfter.addClass("show");
            } else {
                fallSymbolBefore.removeClass("show");
                fallSymbolAfter.removeClass("show");
            }
        } else {
            // 按差价：隐藏符号
            riseSymbolBefore.removeClass("show");
            riseSymbolAfter.removeClass("show");
            fallSymbolBefore.removeClass("show");
            fallSymbolAfter.removeClass("show");
        }
    }
    
    // 增加涨幅值
    function increaseRiseValue() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#riseValue");
        var currentValue = parseFloat(input.val()) || 0;
        var step = $("#riseFallType").val() === "1" ? 0.1 : 0.01;
        var newValue = currentValue + step;
        
        // 检查是否超出范围
        if (newValue > 99.99) {
            $.modal.msgWarning("请输入0.01%~99.99%的有效数值");
            return;
        }
        
        input.val(newValue.toFixed(2));
        updateInputClasses();
        // 更新提示框，并显示（如果有基准价）
        updateRiseValueTooltip(true);
    }
    
    // 减少涨幅值
    function decreaseRiseValue() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#riseValue");
        var currentValue = parseFloat(input.val()) || 0;
        var step = $("#riseFallType").val() === "1" ? 0.1 : 0.01;
        var newValue = currentValue - step;
        
        if (newValue <= 0) {
            input.val('');
            $.modal.msgWarning("请输入0.01%~99.99%的有效数值");
            updateInputClasses();
            // 隐藏提示框
            $("#riseValueTooltip").removeClass('show');
            return;
        }
        
        input.val(newValue.toFixed(2));
        updateInputClasses();
        // 更新提示框，并显示（如果有基准价）
        updateRiseValueTooltip(true);
    }
    
    // 增加跌幅值
    function increaseFallValue() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#fallValue");
        var currentValue = parseFloat(input.val()) || 0;
        var step = $("#riseFallType").val() === "1" ? 0.1 : 0.01;
        var newValue = currentValue + step;
        
        // 检查是否超出范围
        if (newValue > 99.99) {
            $.modal.msgWarning("请输入0.01%~99.99%的有效数值");
            return;
        }
        
        input.val(newValue.toFixed(2));
        updateInputClasses();
        // 更新提示框，并显示（如果有基准价）
        setTimeout(function() {
            updateFallValueTooltip(true);
        }, 10);
    }
    
    // 减少跌幅值
    function decreaseFallValue() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#fallValue");
        var currentValue = parseFloat(input.val()) || 0;
        var step = $("#riseFallType").val() === "1" ? 0.1 : 0.01;
        var newValue = currentValue - step;
        
        if (newValue <= 0) {
            input.val('');
            $.modal.msgWarning("请输入0.01%~99.99%的有效数值");
            updateInputClasses();
            // 隐藏提示框
            $("#fallValueTooltip").removeClass('show');
            return;
        }
        
        input.val(newValue.toFixed(2));
        updateInputClasses();
        // 更新提示框，并显示（如果有基准价）
        setTimeout(function() {
            updateFallValueTooltip(true);
        }, 10);
    }
    
    // 更新涨幅值提示框
    function updateRiseValueTooltip(forceShow) {
        var riseValue = parseFloat($("#riseValue").val()) || 0;
        var basePrice = parseFloat($("#initialBasePrice").val()) || 0;
        var riseFallType = $("#riseFallType").val();
        var tooltip = $("#riseValueTooltip");
        var input = $("#riseValue");
        
        // 只有在有基准价和涨幅值时才显示提示框
        if (riseValue > 0 && basePrice > 0) {
            var displayValue;
            if (riseFallType === "1") {
                // 按百分比：显示计算后的价格
                var calculatedPrice = basePrice * (1 + riseValue / 100);
                displayValue = calculatedPrice.toFixed(2);
            } else {
                // 按差价：显示百分比形式，如 +0.50%
                var percentage = (riseValue / basePrice) * 100;
                displayValue = (percentage >= 0 ? '+' : '') + percentage.toFixed(2) + '%';
            }
            tooltip.text(displayValue);
            // 如果强制显示或输入框有焦点，显示提示框
            if (forceShow || input.is(':focus')) {
                tooltip.addClass('show');
            }
        } else {
            // 如果没有基准价或涨幅值，隐藏提示框
            tooltip.text('');
            tooltip.removeClass('show');
        }
    }
    
    // 更新跌幅值提示框
    function updateFallValueTooltip(forceShow) {
        var fallValue = parseFloat($("#fallValue").val()) || 0;
        var basePrice = parseFloat($("#initialBasePrice").val()) || 0;
        var riseFallType = $("#riseFallType").val();
        var tooltip = $("#fallValueTooltip");
        var input = $("#fallValue");
        
        // 只有在有基准价和跌幅值时才显示提示框
        if (fallValue > 0 && basePrice > 0) {
            var displayValue;
            if (riseFallType === "1") {
                // 按百分比：显示计算后的价格
                var calculatedPrice = basePrice * (1 - fallValue / 100);
                displayValue = calculatedPrice.toFixed(2);
            } else {
                // 按差价：显示百分比形式，如 -0.50%
                var percentage = (fallValue / basePrice) * 100;
                displayValue = (percentage >= 0 ? '-' : '+') + Math.abs(percentage).toFixed(2) + '%';
            }
            tooltip.text(displayValue);
            // 如果强制显示或输入框有焦点，显示提示框
            if (forceShow || input.is(':focus')) {
                tooltip.addClass('show');
            }
        } else {
            // 如果没有基准价或跌幅值，隐藏提示框
            tooltip.text('');
            tooltip.removeClass('show');
        }
    }
    
    // 更新初始市值提示框
    function updateInitialMarketValueTooltip(forceShow) {
        var initialBasePrice = parseFloat($("#initialBasePrice").val()) || 0;
        var initialPosition = parseInt($("#initialPosition").val()) || 0;
        var tooltip = $("#initialMarketValueTooltip");
        var input = $("#initialPosition");
        
        // 只有在有基准价和持仓时才显示提示框
        if (initialBasePrice > 0 && initialPosition > 0) {
            // 计算初始市值 = 初始基准价 * 初始持仓
            var initialMarketValue = initialBasePrice * initialPosition;
            tooltip.text('初始市值' + formatNumber(initialMarketValue) + '元');
            // 如果强制显示或输入框有焦点，显示提示框
            if (forceShow || input.is(':focus')) {
                tooltip.addClass('show');
            }
            
            // 如果初始可用资金为空，自动设置为初始市值的1倍
            var initialAvailableFunds = $("#initialAvailableFunds").val();
            if (!initialAvailableFunds || initialAvailableFunds.trim() === '') {
                $("#initialAvailableFunds").val(initialMarketValue.toFixed(2));
                // 更新按钮高亮状态（1倍）
                updateAvailableFundsButtonsHighlight(1);
            }
        } else {
            // 如果没有基准价或持仓，隐藏提示框
            tooltip.text('');
            tooltip.removeClass('show');
        }
    }
    
    // 格式化手数为单位（手、十手、百手、千手、万手、十万手）
    function formatHandsUnit(hands) {
        if (!hands || hands === 0) {
            return '';
        }
        var num = parseInt(hands);
        if (num < 10) {
            return '手';
        } else if (num < 100) {
            return '十手';
        } else if (num < 1000) {
            return '百手';
        } else if (num < 10000) {
            return '千手';
        } else if (num < 100000) {
            return '万手';
        } else {
            return '十万手';
        }
    }
    
    // 更新手数提示框
    function updateHandsTooltip(inputId, tooltipId) {
        var input = $("#" + inputId);
        var tooltip = $("#" + tooltipId);
        var value = parseInt(input.val()) || 0;
        
        if (value > 0) {
            // 计算手数
            var hands = 0;
            if (currentMinTradeQuantity && currentMinTradeQuantity > 0) {
                hands = Math.floor(value / currentMinTradeQuantity);
            } else {
                // 如果没有最小交易数量，默认1手=1股
                hands = value;
            }
            
            if (hands > 0) {
                var formattedValue = formatHandsUnit(hands);
                // 当格式化值为"手"时不显示提示框，其他情况显示
                if (formattedValue === '手') {
                    tooltip.text('');
                    tooltip.removeClass('show');
                } else {
                    tooltip.text(formattedValue);
                    tooltip.addClass('show');
                }
            } else {
                tooltip.text('');
                tooltip.removeClass('show');
            }
        } else {
            tooltip.text('');
            tooltip.removeClass('show');
        }
    }
    
    // 验证每上涨/每下跌输入值
    function validateRiseFallValue(inputId) {
        var riseFallType = $("#riseFallType").val();
        
        // 如果涨跌类型为"按差价"，不进行验证
        if (riseFallType === "2") {
            return true;
        }
        
        var input = $("#" + inputId);
        var inputValue = input.val();
        
        // 如果输入框为空，不进行验证
        if (!inputValue || inputValue.trim() === '') {
            return true;
        }
        
        var value = parseFloat(inputValue) || 0;
        
        // 如果输入为0，提示错误并清空
        if (value === 0) {
            input.val('');
            $.modal.msgWarning("请输入0.01%~99.99%的有效数值");
            // 更新样式类
            updateInputClasses();
            return false;
        }
        
        // 检查是否在有效范围内（0.01% ~ 99.99%）
        if (value < 0.01 || value > 99.99) {
            $.modal.msgWarning("请输入0.01%~99.99%的有效数值");
            return false;
        }
        
        return true;
    }
    
    // 验证单笔数量是否为最小交易数量的整数倍
    function validateSingleTradeQuantity() {
        var input = $("#singleTradeQuantity");
        var inputValue = input.val();
        
        // 如果输入框为空，不进行验证
        if (!inputValue || inputValue.trim() === '') {
            return true;
        }
        
        var value = parseInt(inputValue) || 0;
        
        // 如果输入为0，提示错误并清空
        if (value === 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            return false;
        }
        
        if (!currentMinTradeQuantity || currentMinTradeQuantity <= 0) {
            // 如果没有最小交易数量，不进行验证
            return true;
        }
        
        if (value > 0 && value % currentMinTradeQuantity !== 0) {
            $.modal.msgWarning("数量应为" + currentMinTradeQuantity + "的整数倍");
            // 不自动调整，只提示错误
            return false;
        }
        
        return true;
    }
    
    // 增加单笔数量
    function increaseSingleTradeQuantity() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#singleTradeQuantity");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue + step;
        input.val(newValue);
        // 验证
        validateSingleTradeQuantity();
        
        // 如果初始持仓为空，自动设置为单笔数量的10倍
        var initialPosition = $("#initialPosition").val();
        if (!initialPosition || initialPosition.trim() === '') {
            if (newValue > 0) {
                setInitialPositionMultiplier(10);
            }
        } else {
            // 更新倍数按钮高亮状态
            updateMultiplierButtonsHighlight();
        }
        
        // 更新手数提示框
        updateHandsTooltip('singleTradeQuantity', 'singleTradeQuantityTooltip');
    }
    
    // 减少单笔数量
    function decreaseSingleTradeQuantity() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#singleTradeQuantity");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue - step;
        
        if (newValue <= 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            // 更新倍数按钮高亮状态（清空时移除高亮）
            updateMultiplierButtonsHighlight();
            // 更新手数提示框（清空时隐藏）
            updateHandsTooltip('singleTradeQuantity', 'singleTradeQuantityTooltip');
            return;
        }
        
        input.val(newValue);
        // 验证
        validateSingleTradeQuantity();
        
        // 如果初始持仓为空，自动设置为单笔数量的10倍
        var initialPosition = $("#initialPosition").val();
        if (!initialPosition || initialPosition.trim() === '') {
            if (newValue > 0) {
                setInitialPositionMultiplier(10);
            }
        } else {
            // 更新倍数按钮高亮状态
            updateMultiplierButtonsHighlight();
        }
        
        // 更新手数提示框
        updateHandsTooltip('singleTradeQuantity', 'singleTradeQuantityTooltip');
    }
    
    // 验证最小持仓是否为最小交易数量的整数倍
    function validatePositionRangeMin() {
        var input = $("#positionRangeMin");
        var inputValue = input.val();
        
        // 如果输入框为空，不进行验证
        if (!inputValue || inputValue.trim() === '') {
            return true;
        }
        
        var value = parseInt(inputValue) || 0;
        
        // 如果输入为0，提示错误并清空
        if (value === 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            return false;
        }
        
        if (!currentMinTradeQuantity || currentMinTradeQuantity <= 0) {
            // 如果没有最小交易数量，不进行验证
            return true;
        }
        
        if (value > 0 && value % currentMinTradeQuantity !== 0) {
            $.modal.msgWarning("数量应为" + currentMinTradeQuantity + "的整数倍");
            // 不自动调整，只提示错误
            return false;
        }
        
        return true;
    }
    
    // 增加最小持仓
    function increasePositionRangeMin() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#positionRangeMin");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue + step;
        input.val(newValue);
        // 验证
        validatePositionRangeMin();
        // 更新手数提示框
        updateHandsTooltip('positionRangeMin', 'positionRangeMinTooltip');
    }
    
    // 减少最小持仓
    function decreasePositionRangeMin() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#positionRangeMin");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue - step;
        
        if (newValue <= 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            // 更新手数提示框（清空时隐藏）
            updateHandsTooltip('positionRangeMin', 'positionRangeMinTooltip');
            return;
        }
        
        input.val(newValue);
        // 验证
        validatePositionRangeMin();
        // 更新手数提示框
        updateHandsTooltip('positionRangeMin', 'positionRangeMinTooltip');
    }
    
    // 验证最大持仓是否为最小交易数量的整数倍
    function validatePositionRangeMax() {
        var input = $("#positionRangeMax");
        var inputValue = input.val();
        
        // 如果输入框为空，不进行验证
        if (!inputValue || inputValue.trim() === '') {
            return true;
        }
        
        var value = parseInt(inputValue) || 0;
        
        // 如果输入为0，提示错误并清空
        if (value === 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            return false;
        }
        
        if (!currentMinTradeQuantity || currentMinTradeQuantity <= 0) {
            // 如果没有最小交易数量，不进行验证
            return true;
        }
        
        if (value > 0 && value % currentMinTradeQuantity !== 0) {
            $.modal.msgWarning("数量应为" + currentMinTradeQuantity + "的整数倍");
            // 不自动调整，只提示错误
            return false;
        }
        
        return true;
    }
    
    // 增加最大持仓
    function increasePositionRangeMax() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#positionRangeMax");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue + step;
        input.val(newValue);
        // 验证
        validatePositionRangeMax();
        // 更新手数提示框
        updateHandsTooltip('positionRangeMax', 'positionRangeMaxTooltip');
    }
    
    // 减少最大持仓
    function decreasePositionRangeMax() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#positionRangeMax");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue - step;
        
        if (newValue <= 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            // 更新手数提示框（清空时隐藏）
            updateHandsTooltip('positionRangeMax', 'positionRangeMaxTooltip');
            return;
        }
        
        input.val(newValue);
        // 验证
        validatePositionRangeMax();
        // 更新手数提示框
        updateHandsTooltip('positionRangeMax', 'positionRangeMaxTooltip');
    }
    
    // 验证初始持仓是否为最小交易数量的整数倍
    function validateInitialPosition() {
        var input = $("#initialPosition");
        var inputValue = input.val();
        
        // 如果输入框为空，不进行验证
        if (!inputValue || inputValue.trim() === '') {
            return true;
        }
        
        var value = parseInt(inputValue) || 0;
        
        // 如果输入为0，提示错误并清空
        if (value === 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            return false;
        }
        
        if (!currentMinTradeQuantity || currentMinTradeQuantity <= 0) {
            // 如果没有最小交易数量，不进行验证
            return true;
        }
        
        if (value > 0 && value % currentMinTradeQuantity !== 0) {
            $.modal.msgWarning("数量应为" + currentMinTradeQuantity + "的整数倍");
            // 不自动调整，只提示错误
            return false;
        }
        
        return true;
    }
    
    // 增加初始持仓
    function increaseInitialPosition() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#initialPosition");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue + step;
        input.val(newValue);
        // 验证
        validateInitialPosition();
        // 更新倍数按钮高亮状态
        updateMultiplierButtonsHighlight();
        // 更新手数提示框
        updateHandsTooltip('initialPosition', 'initialPositionTooltip');
        // 更新初始市值提示
        updateInitialMarketValueTooltip(true);
    }
    
    // 减少初始持仓
    function decreaseInitialPosition() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        var input = $("#initialPosition");
        var currentValue = parseInt(input.val()) || 0;
        var step = currentMinTradeQuantity || 1;
        var newValue = currentValue - step;
        
        if (newValue <= 0) {
            input.val('');
            $.modal.msgWarning("请输入有效数字");
            // 更新倍数按钮高亮状态（清空时移除高亮）
            updateMultiplierButtonsHighlight();
            // 更新手数提示框（清空时隐藏）
            updateHandsTooltip('initialPosition', 'initialPositionTooltip');
            // 更新初始市值提示（清空时隐藏）
            updateInitialMarketValueTooltip(true);
            return;
        }
        
        input.val(newValue);
        // 验证
        validateInitialPosition();
        // 更新倍数按钮高亮状态
        updateMultiplierButtonsHighlight();
        // 更新手数提示框
        updateHandsTooltip('initialPosition', 'initialPositionTooltip');
        // 更新初始市值提示
        updateInitialMarketValueTooltip(true);
    }
    
    // 设置初始持仓为单笔数量的倍数
    function setInitialPositionMultiplier(multiplier) {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        
        // 获取单笔数量
        var singleTradeQuantity = parseInt($("#singleTradeQuantity").val()) || 0;
        if (singleTradeQuantity <= 0) {
            $.modal.msgWarning("请先输入单笔数量");
            return;
        }
        
        // 计算倍数后的值
        var newValue = singleTradeQuantity * multiplier;
        // 向下取整为整数（初始持仓必须是整数）
        newValue = Math.floor(newValue);
        
        // 如果设置了最小交易数量，需要调整到最小交易数量的整数倍
        if (currentMinTradeQuantity && currentMinTradeQuantity > 0) {
            // 向下取整到最小交易数量的整数倍
            newValue = Math.floor(newValue / currentMinTradeQuantity) * currentMinTradeQuantity;
            if (newValue <= 0) {
                newValue = currentMinTradeQuantity;
            }
        }
        
        // 设置到初始持仓输入框
        $("#initialPosition").val(newValue);
        
        // 验证
        validateInitialPosition();
        
        // 更新倍数按钮高亮状态
        updateMultiplierButtonsHighlight();
        
        // 更新手数提示框
        updateHandsTooltip('initialPosition', 'initialPositionTooltip');
        
        // 更新初始市值提示
        updateInitialMarketValueTooltip(true);
    }
    
    // 显示自定义倍数输入框
    function showCustomMultiplierInput() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        
        // 获取单笔数量
        var singleTradeQuantity = parseInt($("#singleTradeQuantity").val()) || 0;
        if (singleTradeQuantity <= 0) {
            $.modal.msgWarning("请先输入单笔数量");
            return;
        }
        
        // 显示自定义倍数模态框
        var modal = $("#customMultiplierModal");
        var modalContent = modal.find(".custom-multiplier-modal-content");
        var button = $(".custom-multiplier-btn-wrapper button");
        
        // 定位模态框在按钮右上方
        
        modalContent.css({
            'bottom': '100%',
            'right': '0',
            'margin-bottom': '5px'
        });
        
        modal.show();
        $("#customMultiplierInput").val("").focus();
        $("#customMultiplierError").hide();
        
        // 限制输入只能输入整数（不允许小数点）
        $("#customMultiplierInput").off('input').on('input', function(e) {
            var value = $(this).val();
            // 只允许数字
            var newValue = value.replace(/[^\d]/g, '');
            if (value !== newValue) {
                $(this).val(newValue);
            }
        });
        
        // 绑定回车键事件
        $("#customMultiplierInput").off('keypress').on('keypress', function(e) {
            if (e.which === 13) { // 回车键
                confirmCustomMultiplier();
            }
        });
    }
    
    // 隐藏自定义倍数模态框
    function hideCustomMultiplierModal() {
        $("#customMultiplierModal").hide();
        $("#customMultiplierInput").val("");
        $("#customMultiplierError").hide();
    }
    
    // 确认自定义倍数
    function confirmCustomMultiplier() {
        var value = $("#customMultiplierInput").val().trim();
        var errorDiv = $("#customMultiplierError");
        
        // 隐藏错误提示
        errorDiv.hide();
        
        if (!value || value === '') {
            errorDiv.text("请输入自定义倍数").show();
            return;
        }
        
        var multiplier = parseInt(value);
        if (isNaN(multiplier) || multiplier <= 0) {
            errorDiv.text("请输入有效的倍数（大于0的整数）").show();
            return;
        }
        
        // 设置初始持仓为自定义倍数
        setInitialPositionMultiplier(multiplier);
        
        // 隐藏模态框
        hideCustomMultiplierModal();
    }
    
    // 更新倍数按钮高亮状态
    function updateMultiplierButtonsHighlight() {
        // 移除所有按钮的active类
        $(".trigger-condition-multiplier-btn").removeClass('active');
        
        // 如果没有选择证券或没有输入单笔数量，不进行高亮
        if (!isSecuritySelected()) {
            return;
        }
        
        var singleTradeQuantity = parseInt($("#singleTradeQuantity").val()) || 0;
        if (singleTradeQuantity <= 0) {
            return;
        }
        
        var initialPosition = parseInt($("#initialPosition").val()) || 0;
        if (initialPosition <= 0) {
            return;
        }
        
        // 检查初始持仓是否是某个倍数
        var multipliers = [5, 10, 15, 20];
        multipliers.forEach(function(multiplier) {
            var expectedValue = singleTradeQuantity * multiplier;
            
            // 如果设置了最小交易数量，需要调整期望值
            if (currentMinTradeQuantity && currentMinTradeQuantity > 0) {
                expectedValue = Math.floor(expectedValue / currentMinTradeQuantity) * currentMinTradeQuantity;
            }
            
            // 如果初始持仓等于期望值，高亮对应的按钮
            if (initialPosition === expectedValue) {
                $(".trigger-condition-multiplier-btn").each(function() {
                    var btnText = $(this).text();
                    var btnMultiplier = parseInt(btnText.replace('倍', ''));
                    if (btnMultiplier === multiplier) {
                        $(this).addClass('active');
                    }
                });
            }
        });
    }
    
    // 禁用所有输入项
    function disableAllInputs() {
        // 禁用日期选择器 - 使用readonly而不是disabled，以便点击事件可以触发
        if (startDatePicker) {
            $("#startDate").prop('readonly', true).addClass('form-control-disabled');
        }
        if (endDatePicker) {
            $("#endDate").prop('readonly', true).addClass('form-control-disabled');
        }
        
        // 禁用触发条件输入项 - 使用readonly而不是disabled，以便点击事件可以触发
        $("#riseFallType").prop('disabled', true).addClass('disabled');
        $("#initialBasePrice").prop('readonly', true).addClass('form-control-disabled');
        $("#riseValue").prop('readonly', true).addClass('form-control-disabled');
        $("#fallValue").prop('readonly', true).addClass('form-control-disabled');
        $(".trigger-condition-input-group").addClass('disabled');
        
        // 禁用委托设置输入项 - 使用readonly而不是disabled，以便点击事件可以触发
        $("#singleTradeQuantity").prop('readonly', true).addClass('form-control-disabled');
        $("#initialPosition").prop('readonly', true).addClass('form-control-disabled');
        $("#initialAvailableFunds").prop('readonly', true).addClass('form-control-disabled');
        
        // 禁用高级设置输入项 - 使用readonly而不是disabled，以便点击事件可以触发
        $("#priceRangeMin").prop('readonly', true).addClass('form-control-disabled');
        $("#priceRangeMax").prop('readonly', true).addClass('form-control-disabled');
        $("#positionRangeMin").prop('readonly', true).addClass('form-control-disabled');
        $("#positionRangeMax").prop('readonly', true).addClass('form-control-disabled');
        // 禁用倍数委托开关
        $("#multiplierOrder").prop('disabled', true);
        
        // 禁用手续费设置输入项
        $("#commissionTenThousandth").prop('readonly', true).addClass('form-control-disabled');
        $("#freeMinimumCommission").prop('disabled', true);
        
        // 禁用倍数按钮
        $(".trigger-condition-multiplier-btn").prop('disabled', true);
        
        // 禁用日期范围快捷选择按钮
        $(".date-range-btn").prop('disabled', true);
        
        // 禁用初始可用资金快捷选择按钮
        $(".available-funds-btn").prop('disabled', true);
        
        // 禁用开始回测按钮
        $(".btn-primary").prop('disabled', true);
    }
    
    // 启用所有输入项
    function enableAllInputs() {
        // 启用日期选择器
        if (startDatePicker) {
            $("#startDate").prop('readonly', false).removeClass('form-control-disabled');
        }
        if (endDatePicker) {
            $("#endDate").prop('readonly', false).removeClass('form-control-disabled');
        }
        
        // 启用触发条件输入项
        $("#riseFallType").prop('disabled', false).removeClass('disabled');
        $("#initialBasePrice").prop('readonly', false).removeClass('form-control-disabled');
        $("#riseValue").prop('readonly', false).removeClass('form-control-disabled');
        $("#fallValue").prop('readonly', false).removeClass('form-control-disabled');
        $(".trigger-condition-input-group").removeClass('disabled');
        
        // 启用委托设置输入项
        $("#singleTradeQuantity").prop('readonly', false).removeClass('form-control-disabled');
        $("#initialPosition").prop('readonly', false).removeClass('form-control-disabled');
        $("#initialAvailableFunds").prop('readonly', false).removeClass('form-control-disabled');
        
        // 启用高级设置输入项
        $("#priceRangeMin").prop('readonly', false).removeClass('form-control-disabled');
        $("#priceRangeMax").prop('readonly', false).removeClass('form-control-disabled');
        $("#positionRangeMin").prop('readonly', false).removeClass('form-control-disabled');
        $("#positionRangeMax").prop('readonly', false).removeClass('form-control-disabled');
        // 启用倍数委托开关
        $("#multiplierOrder").prop('disabled', false);
        
        // 启用手续费设置输入项
        $("#commissionTenThousandth").prop('readonly', false).removeClass('form-control-disabled');
        $("#freeMinimumCommission").prop('disabled', false);
        
        // 启用倍数按钮
        $(".trigger-condition-multiplier-btn").prop('disabled', false);
        
        // 启用日期范围快捷选择按钮
        $(".date-range-btn").prop('disabled', false);
        
        // 启用初始可用资金快捷选择按钮
        $(".available-funds-btn").prop('disabled', false);
        
        // 启用开始回测按钮
        $(".btn-primary").prop('disabled', false);
    }
    
    // 检查证券是否已选择
    function isSecuritySelected() {
        var symbol = $("#securitySymbol").val();
        return symbol && symbol.trim() !== '';
    }
    
    // 填充昨日收盘价
    function fillPreviousClosePrice() {
        // 关闭下拉菜单
        $("#basePriceDropdown").removeClass('show');
        
        // 获取开始日期
        var startDate = startDatePicker ? startDatePicker.getSelectedDate() : $("#startDate").val();
        
        if (!startDate) {
            $.modal.msgWarning("请先选择回测开始日期");
            return;
        }
        
        // 获取证券代码
        var symbol = $("#securitySymbol").val();
        if (!symbol) {
            $.modal.msgWarning("请先选择证券");
            return;
        }
        
        // 调用接口获取开始日期的昨日收盘价
        $.ajax({
            url: ctx + "security/time-share/data",
            type: "GET",
            data: {
                symbol: symbol,
                startDate: startDate,
                endDate: startDate
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 0 && data.data && data.data.securityInfo) {
                    var previousClosePrice = data.data.securityInfo.previousClosePrice;
                    if (previousClosePrice) {
                        $("#initialBasePrice").val(parseFloat(previousClosePrice).toFixed(2));
                        $.modal.msgSuccess("已填充开始日昨收价");
                        // 更新提示框
                        updateRiseValueTooltip(true);
                        updateFallValueTooltip(true);
                        updateInitialMarketValueTooltip(true);
                    } else {
                        // 数据为空，调用同步分时接口
                        syncTimeshareDataAndFillPrice(symbol, startDate);
                    }
                } else {
                    // 数据为空，调用同步分时接口
                    syncTimeshareDataAndFillPrice(symbol, startDate);
                }
            },
            error: function(xhr, status, error) {
                console.error("获取昨日收盘价失败:", error);
                // 出错时也尝试同步数据
                syncTimeshareDataAndFillPrice(symbol, startDate);
            }
        });
    }
    
    // 保存表单参数到sessionStorage
    function saveFormParams() {
        var formParams = {
            symbol: $("#securitySymbol").val(),
            startDate: startDatePicker ? startDatePicker.getSelectedDate() : $("#startDate").val(),
            endDate: endDatePicker ? endDatePicker.getSelectedDate() : $("#endDate").val(),
            initialBasePrice: $("#initialBasePrice").val(),
            riseValue: $("#riseValue").val(),
            fallValue: $("#fallValue").val(),
            riseFallType: $("#riseFallType").val(),
            singleTradeQuantity: $("#singleTradeQuantity").val(),
            initialPosition: $("#initialPosition").val(),
            initialAvailableFunds: $("#initialAvailableFunds").val(),
            priceRangeMin: $("#priceRangeMin").val(),
            priceRangeMax: $("#priceRangeMax").val(),
            positionRangeMin: $("#positionRangeMin").val(),
            positionRangeMax: $("#positionRangeMax").val(),
            multiplierOrder: $("#multiplierOrder").is(':checked'),
            commissionTenThousandth: $("#commissionTenThousandth").val(),
            freeMinimumCommission: $("#freeMinimumCommission").is(':checked')
        };
        sessionStorage.setItem('gridTradingBacktestFormParams', JSON.stringify(formParams));
    }
    
    // 从sessionStorage恢复表单参数
    function restoreFormParams() {
        var savedParams = sessionStorage.getItem('gridTradingBacktestFormParams');
        if (savedParams) {
            try {
                var formParams = JSON.parse(savedParams);
                
                // 恢复证券代码
                if (formParams.symbol) {
                    $("#securitySymbol").val(formParams.symbol);
                    // 如果证券选择器已初始化，尝试设置选中的证券
                    if (securitySelector && securitySelector.securitiesList) {
                        var targetSecurity = securitySelector.securitiesList.find(function(security) {
                            return security.symbol === formParams.symbol;
                        });
                        if (targetSecurity) {
                            securitySelector.setSelectedSecurity(targetSecurity);
                        }
                    }
                }
                
                // 恢复日期
                if (formParams.startDate && startDatePicker) {
                    startDatePicker.setDate(formParams.startDate);
                } else if (formParams.startDate) {
                    $("#startDate").val(formParams.startDate);
                }
                
                if (formParams.endDate && endDatePicker) {
                    endDatePicker.setDate(formParams.endDate);
                } else if (formParams.endDate) {
                    $("#endDate").val(formParams.endDate);
                }
                
                // 恢复其他表单字段
                if (formParams.initialBasePrice) $("#initialBasePrice").val(formParams.initialBasePrice);
                if (formParams.riseValue) $("#riseValue").val(formParams.riseValue);
                if (formParams.fallValue) $("#fallValue").val(formParams.fallValue);
                if (formParams.riseFallType) $("#riseFallType").val(formParams.riseFallType);
                if (formParams.singleTradeQuantity) $("#singleTradeQuantity").val(formParams.singleTradeQuantity);
                if (formParams.initialPosition) $("#initialPosition").val(formParams.initialPosition);
                if (formParams.initialAvailableFunds) $("#initialAvailableFunds").val(formParams.initialAvailableFunds);
                if (formParams.priceRangeMin) $("#priceRangeMin").val(formParams.priceRangeMin);
                if (formParams.priceRangeMax) $("#priceRangeMax").val(formParams.priceRangeMax);
                if (formParams.positionRangeMin) $("#positionRangeMin").val(formParams.positionRangeMin);
                if (formParams.positionRangeMax) $("#positionRangeMax").val(formParams.positionRangeMax);
                if (formParams.multiplierOrder !== undefined) $("#multiplierOrder").prop('checked', formParams.multiplierOrder);
                if (formParams.commissionTenThousandth) $("#commissionTenThousandth").val(formParams.commissionTenThousandth);
                if (formParams.freeMinimumCommission !== undefined) $("#freeMinimumCommission").prop('checked', formParams.freeMinimumCommission);
                
                // 更新提示框
                updateRiseValueTooltip(true);
                updateFallValueTooltip(true);
                updateInitialMarketValueTooltip(true);
                
                // 清除保存的参数
                sessionStorage.removeItem('gridTradingBacktestFormParams');
            } catch (e) {
                console.error("恢复表单参数失败:", e);
            }
        }
    }
    
    // 显示同步数据确认弹窗
    function showSyncDataModal(errorMsg, symbol, startDate, endDate) {
        // 使用确认弹窗询问是否去同步分时数据
        $.modal.confirm(errorMsg + "<br/><br/>是否前往同步分时数据？", function() {
            // 保存表单参数
            saveFormParams();
            
            // 用户点击确定，跳转到日分时页面
            // 构建返回URL，包含当前页面的所有参数
            var returnUrl = window.location.pathname + window.location.search;
            var url = ctx + "security/time-share?sync=true&symbol=" + encodeURIComponent(symbol) + 
                      "&startDate=" + encodeURIComponent(startDate) + 
                      "&endDate=" + encodeURIComponent(endDate) +
                      "&returnUrl=" + encodeURIComponent(returnUrl);
            window.location.href = url;
        });
    }
    
    // 同步分时数据并填充基准价
    function syncTimeshareDataAndFillPrice(symbol, startDate) {
        // 显示开始同步的提示
        $.modal.msgSuccess("开始同步开始日分时数据，请稍候...");
        
        // 调用同步分时接口（异步，返回任务ID）
        $.ajax({
            url: ctx + "security/time-share/sync",
            type: "POST",
            data: {
                symbol: symbol,
                startDate: startDate,
                endDate: startDate
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 0) {
                    var taskId = data.data;
                    
                    if (!taskId) {
                        // 无需同步，直接获取数据
                        fetchPreviousClosePrice(symbol, startDate);
                        return;
                    }
                    
                    // 轮询任务进度，直到完成
                    pollSyncTaskProgress(taskId, symbol, startDate);
                } else {
                    // 同步失败
                    $.modal.msgError(data.msg || "同步分时数据失败");
                }
            },
            error: function(xhr, status, error) {
                console.error("同步分时数据失败:", error);
                var errorMsg = "同步分时数据失败";
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                $.modal.msgError(errorMsg);
            }
        });
    }
    
    // 轮询同步任务进度
    function pollSyncTaskProgress(taskId, symbol, startDate) {
        var pollInterval = setInterval(function() {
            $.ajax({
                url: ctx + "security/time-share/sync/progress",
                type: "GET",
                data: {
                    taskId: taskId
                },
                dataType: 'json',
                success: function(data) {
                    if (data.code === 0 && data.data) {
                        var progressData = data.data;
                        
                        // 检查任务状态
                        if (progressData.status === "COMPLETED") {
                            // 同步完成
                            clearInterval(pollInterval);
                            $.modal.msgSuccess("同步完成，正在获取昨收价...");
                            
                            // 延迟一下再获取数据，确保数据已保存
                            setTimeout(function() {
                                fetchPreviousClosePrice(symbol, startDate);
                            }, 1000);
                        } else if (progressData.status === "FAILED") {
                            // 同步失败
                            clearInterval(pollInterval);
                            var errorMsg = progressData.errorMessage || "同步分时数据失败";
                            $.modal.msgError(errorMsg);
                        }
                        // 如果状态是 RUNNING，继续轮询
                    } else {
                        // 查询失败，可能是任务不存在
                        if (data.msg && data.msg.indexOf("任务不存在") !== -1) {
                            clearInterval(pollInterval);
                            $.modal.msgError("同步任务不存在或已过期");
                        }
                    }
                },
                error: function(xhr, status, error) {
                    console.error("查询同步进度失败:", error);
                    // 系统服务错误，停止轮询
                    clearInterval(pollInterval);
                    var errorMsg = "查询同步进度失败";
                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMsg = xhr.responseJSON.msg;
                    } else if (error) {
                        errorMsg = error;
                    }
                    $.modal.msgError(errorMsg);
                }
            });
        }, 1000); // 每1秒轮询一次
        
        // 设置超时，30秒后停止轮询
        setTimeout(function() {
            clearInterval(pollInterval);
        }, 30000);
    }
    
    // 获取昨日收盘价并填充
    function fetchPreviousClosePrice(symbol, startDate) {
        $.ajax({
            url: ctx + "security/time-share/data",
            type: "GET",
            data: {
                symbol: symbol,
                startDate: startDate,
                endDate: startDate
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 0 && data.data && data.data.securityInfo) {
                    var previousClosePrice = data.data.securityInfo.previousClosePrice;
                    if (previousClosePrice) {
                        $("#initialBasePrice").val(parseFloat(previousClosePrice).toFixed(2));
                        $.modal.msgSuccess("同步完成，已填充开始日昨收价");
                        // 更新提示框
                        updateRiseValueTooltip(true);
                        updateFallValueTooltip(true);
                        updateInitialMarketValueTooltip(true);
                    } else {
                        $.modal.msgWarning("同步完成，但未找到开始日昨收价数据");
                    }
                } else {
                    $.modal.msgWarning(data.msg || "获取昨日收盘价失败");
                }
            },
            error: function(xhr, status, error) {
                console.error("获取昨日收盘价失败:", error);
                $.modal.msgError("获取昨日收盘价失败，请稍后重试");
            }
        });
    }
    
    
    // 设置初始可用资金为初始市值的倍数
    function setAvailableFundsMultiplier(multiplier) {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        
        // 获取初始基准价
        var initialBasePrice = parseFloat($("#initialBasePrice").val()) || 0;
        if (initialBasePrice <= 0) {
            $.modal.msgWarning("请先输入初始基准价");
            return;
        }
        
        // 获取初始持仓
        var initialPosition = parseInt($("#initialPosition").val()) || 0;
        if (initialPosition <= 0) {
            $.modal.msgWarning("请先输入初始持仓");
            return;
        }
        
        // 计算初始市值 = 初始基准价 * 初始持仓
        var initialMarketValue = initialBasePrice * initialPosition;
        
        // 计算初始可用资金 = 初始市值 * 倍数
        var availableFunds = initialMarketValue * multiplier;
        
        // 设置到初始可用资金输入框（保留2位小数）
        $("#initialAvailableFunds").val(availableFunds.toFixed(2));
        
        // 更新按钮高亮状态
        updateAvailableFundsButtonsHighlight(multiplier);
    }
    
    // 更新初始可用资金按钮高亮状态
    function updateAvailableFundsButtonsHighlight(selectedMultiplier) {
        $(".available-funds-btn").each(function() {
            var btn = $(this);
            var btnText = btn.text();
            var btnMultiplier = null;
            
            if (btnText === '0.25倍') {
                btnMultiplier = 0.25;
            } else if (btnText === '0.5倍') {
                btnMultiplier = 0.5;
            } else if (btnText === '1倍') {
                btnMultiplier = 1;
            } else if (btnText === '1.5倍') {
                btnMultiplier = 1.5;
            }
            
            if (btnMultiplier !== null) {
                if (Math.abs(btnMultiplier - selectedMultiplier) < 0.001) { // 浮点数比较
                    btn.addClass('active');
                } else {
                    btn.removeClass('active');
                }
            }
        });
    }
    
    // 显示自定义初始可用资金倍数输入框
    function showCustomAvailableFundsMultiplierInput() {
        if (!isSecuritySelected()) {
            $.modal.msgWarning("请先选择证券标的");
            return;
        }
        
        // 获取初始基准价
        var initialBasePrice = parseFloat($("#initialBasePrice").val()) || 0;
        if (initialBasePrice <= 0) {
            $.modal.msgWarning("请先输入初始基准价");
            return;
        }
        
        // 获取初始持仓
        var initialPosition = parseInt($("#initialPosition").val()) || 0;
        if (initialPosition <= 0) {
            $.modal.msgWarning("请先输入初始持仓");
            return;
        }
        
        // 显示自定义倍数模态框
        var modal = $("#customAvailableFundsMultiplierModal");
        var modalContent = modal.find(".custom-multiplier-modal-content");
        var button = $(".available-funds-buttons .custom-multiplier-btn-wrapper button");
        
        // 定位模态框在按钮右上方
        modalContent.css({
            'bottom': '100%',
            'right': '0',
            'margin-bottom': '5px'
        });
        
        modal.show();
        $("#customAvailableFundsMultiplierInput").val("").focus();
        $("#customAvailableFundsMultiplierError").hide();
        
        // 限制输入只能输入数字和小数点
        $("#customAvailableFundsMultiplierInput").off('input').on('input', function(e) {
            var value = $(this).val();
            // 只允许数字和小数点
            var newValue = value.replace(/[^\d.]/g, '');
            // 只允许一个小数点
            var parts = newValue.split('.');
            if (parts.length > 2) {
                newValue = parts[0] + '.' + parts.slice(1).join('');
            }
            if (value !== newValue) {
                $(this).val(newValue);
            }
        });
        
        // 绑定回车键事件
        $("#customAvailableFundsMultiplierInput").off('keypress').on('keypress', function(e) {
            if (e.which === 13) { // 回车键
                confirmCustomAvailableFundsMultiplier();
            }
        });
    }
    
    // 隐藏自定义初始可用资金倍数模态框
    function hideCustomAvailableFundsMultiplierModal() {
        $("#customAvailableFundsMultiplierModal").hide();
        $("#customAvailableFundsMultiplierInput").val("");
        $("#customAvailableFundsMultiplierError").hide();
    }
    
    // 确认自定义初始可用资金倍数
    function confirmCustomAvailableFundsMultiplier() {
        var value = $("#customAvailableFundsMultiplierInput").val().trim();
        var errorDiv = $("#customAvailableFundsMultiplierError");
        
        // 隐藏错误提示
        errorDiv.hide();
        
        if (!value || value === '') {
            errorDiv.text("请输入自定义倍数").show();
            return;
        }
        
        var multiplier = parseFloat(value);
        if (isNaN(multiplier) || multiplier <= 0) {
            errorDiv.text("请输入大于0的有效数字").show();
            return;
        }
        
        // 设置初始可用资金为自定义倍数
        setAvailableFundsMultiplier(multiplier);
        
        // 隐藏模态框
        hideCustomAvailableFundsMultiplierModal();
    }
</script>
</body>
</html>

